在Linux上的.NET应用程序中使用谷歌OAuth2授权,需要遵循以下步骤:
dotnet add package Google.Apis.Auth
{
"GoogleOAuth2": {
"ClientId": "your_client_id",
"ClientSecret": "your_client_secret",
"RedirectUri": "http://localhost"
}
}
将your_client_id
和your_client_secret
替换为从谷歌API控制台下载的凭据文件中的相应值。
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.Threading.Tasks;
public class GoogleOAuth2Helper
{
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _redirectUri;
public GoogleOAuth2Helper(IConfiguration configuration)
{
_clientId = configuration["GoogleOAuth2:ClientId"];
_clientSecret = configuration["GoogleOAuth2:ClientSecret"];
_redirectUri = configuration["GoogleOAuth2:RedirectUri"];
}
public async Task<string> AuthorizeAsync()
{
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = _clientId,
ClientSecret = _clientSecret
},
new[] { "https://www.googleapis.com/auth/userinfo.email" },
"user",
CancellationToken.None);
return credential.Token.AccessToken;
}
}
AuthorizeAsync
方法:var googleOAuth2Helper = new GoogleOAuth2Helper(Configuration);
var accessToken = await googleOAuth2Helper.AuthorizeAsync();
领取专属 10元无门槛券
手把手带您无忧上云