我正在使用 ASP.NET Core 7.0 MVC。 我已按照 https://learn.microsoft.com/aspnet/core/security/authentication/social/google-logins 设置我的谷歌登录:
WebApplicationBuilder webApplicationBuilder = WebApplication.CreateBuilder(args);
ConfigurationManager configurationManager = webApplicationBuilder.Configuration;
IServiceCollection serviceDescriptors = webApplicationBuilder.Services;
serviceDescriptors.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(googleOptions => {
googleOptions.ClientId = webApplicationBuilder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = webApplicationBuilder.Configuration["Authentication:Google:ClientSecret"];
googleOptions.Scope.Add("CalendarService.Scope.CalendarReadonly");
googleOptions.SaveTokens = true;
});
现在我需要像这样连接到 Google Calendar API:
GoogleCredential? cred = GoogleCredential.FromAccessToken(token);
CalendarService service = new CalendarService(new BaseClientService.Initializer {
HttpClientInitializer = cred,
ApplicationName = ApplicationName
});
EventsResource.ListRequest request = service.Events.List("primary");
request.ShowDeleted = false;
request.SingleEvents = true;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Events events;
events = request.Execute();
我搜索了很多资源,但我无法从登录中找到登录令牌,有人可以帮助我吗?
我想找到用户AccessToken来访问Google Calendar API。
如果您想获取访问令牌,可以添加保存令牌的选项,然后在 OnCreatingTicket 方法时获取它。
更多详情,可以参考以下代码:
builder.Services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = "Google"; // Use the scheme name you've configured for Google authentication
}).AddGoogle("Google",googleOptions =>
{
googleOptions.ClientId = " ";
googleOptions.ClientSecret = " ";
googleOptions.SaveTokens = true;
googleOptions.Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
var accessToken = context.AccessToken;
//then you could store the access token inside the claims and use it later
var identity = (ClaimsIdentity)context.Principal.Identity;
identity.AddClaim(new Claim("access_token", accessToken));
return Task.CompletedTask;
}
};
});
结果: