从根本上说,我不理解OAuth、Google和Google api。我在Asp工作的v3库。Net Core 1.0。我使用Google Authentication:
app.UseGoogleAuthentication(new GoogleOptions
{
ClientId = Configuration["Google:ClientId"],
ClientSecret = Configuration["Google:ClientSecret"],
Scope = {
"email",
"https://www.googleapis.com/auth/userinfo.email",
"profile",
"https://www.googleapis.com/auth/userinfo.profile",
"openid",
"https://www.googleapis.com/auth/calendar",
},
AccessType = "offline",
SaveTokens = true,
});
很简单。然后我想用谷歌日历。然而,我不能始终获得访问/刷新令牌(老实说,在这一点上,我不确定我理解这些是什么)。我使用这段代码从google取回一个日历服务:
private AuthorizationCodeFlow CreateFlow(IEnumerable<string> scopes)
{
return new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
{
ClientId = _ClientId,
ClientSecret = _ClientSecret
},
DataStore = new MemoryDataStore(),
Scopes = scopes
});
}
private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
{
var flow = CreateFlow(scopes);
var token = await context.GetGoogleTokenResponse();
UserCredential credential = new UserCredential(flow, providerKey, token);
return credential;
}
public async Task<CalendarService> CreateCalendarServiceAsync(HttpContext context, string providerKey)
{
if (string.IsNullOrWhiteSpace(providerKey)) return null;
if (context == null) return null;
var credential = await CreateUserCredential(context, providerKey, new[] { "https://www.googleapis.com/auth/calendar" });
CalendarService service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = _ApplicationName,
});
return service;
}
public static async Task<TokenResponse> GetGoogleTokenResponse(this HttpContext context)
{
var info = await context.Authentication.GetAuthenticateInfoAsync("Google");
if (info == null) return null;
var token = new TokenResponse
{
AccessToken = info.Properties.Items[".Token.access_token"],
RefreshToken = info.Properties.Items[".Token.refresh_token"],
TokenType = info.Properties.Items[".Token.token_type"],
Issued = DateTime.Parse(info.Properties.Items[".issued"]),
};
return token;
}
这是我知道如何获得当前访问/刷新令牌的唯一方法。我错过了什么?有时存在,有时不存在。. net Core 1.0版本的文档最多只能说是很精简。关于通过Asp访问Google api的更好方法的任何帮助。网络核心?
由于您已经设置了SaveTokens = true
,您可以像这样获得access_token: await context.Authentication.GetTokenAsync("access_token");
所以像下面这样改变你的方法可能会解决你的问题:
private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
{
var flow = CreateFlow(scopes);
var token = await context.Authentication.GetTokenAsync("access_token");
UserCredential credential = new UserCredential(flow, providerKey, token);
return credential;
}