Search code examples
c#asp.net-coregoogle-oauthasp.net-core-identity

How can I get a refresh-token from Google OAUTH in ASP.Net Core 5 Identity?


How do you get a refresh-token from Google in ASP.Net Core Identity 5?

I am able to get an access-token, but not a refresh-token.

Startup.cs, ConfigureServices

...
services.AddAuthentication()
    .AddGoogle(options =>
    {
        IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google");

        options.ClientId = googleAuthNSection["ClientId"];
        options.ClientSecret = googleAuthNSection["ClientSecret"];

        options.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
        options.Scope.Add("https://www.googleapis.com/auth/userinfo.profile");
        options.Scope.Add("https://www.googleapis.com/auth/calendar");

        //this should enable a refresh-token, or so I believe
        options.AccessType = "offline"; 

        options.SaveTokens = true;

        options.Events.OnCreatingTicket = ctx =>
        {
            List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();

            tokens.Add(new AuthenticationToken()
            {
                Name = "TicketCreated",
                Value = DateTime.UtcNow.ToString()
            });

            ctx.Properties.StoreTokens(tokens);

            return Task.CompletedTask;
        };
    });

When I sign up with a google account and the code hits "OnCreatingTicket", I get an access token - but no refresh-token...:

enter image description here

Question

What am I missing to get a refresh-token back here?


Solution

  • The code was actually working just fine.

    However, you only get a refresh-token back from Google the first time you register with a new account for the specific OAuth 2.0 Client Id. I was deleting my local user data and signing up again - but this does not make google send the refresh-token again - only access token.

    If you want to use the refresh-token offline, you also need to store it somewhere (like in the database) yourself - this does not happen with the above code.