azureazure-active-directoryblazoropenid-connect

How to automatically refresh access token


I have an api with the following scopes (api_access and offline_access):

api scopes

And a front end blazor app that uses code flow and consumes that api. Here's how I'm configuring authentication:

builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.Authority = "xxxxx";
                options.ClientId = "xxxxx";

                options.ResponseType = "code";

                options.SaveTokens = true;

             options.Scope.Add("api://xxxxx/api_access");

               options.ClientSecret = "xxxxx";

And here's how I'm requesting the access code to call the api:

var access_token = await httpContext.GetTokenAsync("access_token");

This works, but the access token expires in one hour. I don't get a new token when I call httpContext.GetTokenAsync("access_token") again after it is expired. How to get a new valid token?


Solution

  • Depending on your design, you can use refresh_token to get new access_token. You need to call the /token endpoint with your refresh_token.

    Example copied from documentation.

    POST /{tenant}/oauth2/v2.0/token HTTP/1.1
    Host: https://login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=00001111-aaaa-2222-bbbb-3333cccc4444
    &scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
    &refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
    &grant_type=refresh_token
    &client_secret=sampleCredentia1s
    

    Here is what Microsoft says about this

    However, is probably some library which handles that client side chore.