Search code examples
asp.net-mvcasp.net-core-mvcgoogle-oauthgoogle-calendar-apiaccess-token

ASP.NET Core MVC Google Authentication Token


I'm using ASP.NET Core 7.0 MVC. I have followed https://learn.microsoft.com/aspnet/core/security/authentication/social/google-logins to set up my google login:

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;
});

And now I need to connect to Google Calendar API like this:

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();

I have searched a lot of resources, but I can't find the login token from the login, can anyone help me?

I want to find the user AccessToken to access Google Calendar API.


Solution

  • If you want to get the access token, you could add the option to save the token and then get it when OnCreatingTicket method.

    More details, you could refer to below codes:

     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;
    
           }
        };
    });
    

    Result:

    enter image description here


    If you want to get the refresh token or else, you could modify the codes like below:

    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.Scope.Add("https://www.googleapis.com/auth/userinfo.profile");
        googleOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
        googleOptions.AccessType = "offline"; // Request a refresh token
    
        googleOptions.Events = new OAuthEvents
        {
            OnCreatingTicket = context =>
           {
    
               var accessToken = context.AccessToken;
    
               var re = context.RefreshToken;
    
               return Task.CompletedTask;
    
           }
        };
    });
    

    Result:

    enter image description here