Open Closed

Refresh Token Usage in Blazor Server When Access Token Expires #9601


User avatar
0
yunusemrecaglar created

Hello, In a Blazor Server application, I want to refresh the access token using a refresh token when the token expires. How can I do this?


24 Answer(s)
  • User Avatar
    0
    AI-Bot created
    Support Team ABP Agent

    To refresh the access token using a refresh token in a Blazor Server application with ABP, follow these steps:

    1. Request the offline_access scope:
      • In your authentication configuration (typically in Startup.cs or the module class), add the offline_access scope to the OpenIdConnect options:
    options.Scope.Add("offline_access");
    
    • This ensures the refresh_token is issued by the server.
    1. Ensure cookie and refresh token lifetimes are aligned:
      • The default ABP Blazor Server template uses cookie authentication. Set the cookie expiration to match the refresh token lifetime:
    .AddCookie("Cookies", options =>
         {
             options.ExpireTimeSpan = TimeSpan.FromDays(365); // Example: 1 year
         })
    
    • It is recommended to keep Cookie ExpireTimeSpan and the Refresh Token lifetime the same.
    1. Handle token expiration and refresh:

      • ABP does not automatically refresh the access token in Blazor Server. You need to implement logic to detect token expiration and use the refresh token to obtain a new access token.
      • You can use the OidcClient or similar libraries to perform the refresh token flow, or call the token endpoint manually with the refresh_token grant type.
    2. Sign out users after token expiration (optional but recommended):

      • ABP provides extension methods to sign out users after the access token expires. This ensures the UI reflects the authentication state correctly.
      • See the following PR for reference and code you can adapt:
        https://github.com/abpframework/abp/pull/15876
    3. Example: Adding offline_access and configuring OpenIdConnect in Blazor Server

    services.AddAuthentication(options =>
       {
           options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
           options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
       })
       .AddCookie("Cookies", options =>
       {
           options.ExpireTimeSpan = TimeSpan.FromDays(365);
       })
       .AddOpenIdConnect(options =>
       {
           // ... other options ...
           options.Scope.Add("offline_access");
       });
    
    1. Refreshing the token:
      • When the access token expires, use the refresh token to request a new access token from the token endpoint:
    var response = await httpClient.RequestRefreshTokenAsync(new RefreshTokenRequest
         {
             Address = disco.TokenEndpoint,
             ClientId = "your-client-id",
             ClientSecret = "your-client-secret",
             RefreshToken = "your-refresh-token"
         });
    
    • Store the new access and refresh tokens securely.

    For a complete example and more details, see the official ABP documentation and community articles below.

    Sources:


    This response was generated by AI. If it didn’t solve your problem, feel free to post a new answer — our support team will jump in to help you soon.

  • User Avatar
    0
    yunusemrecaglar created

    In my Blazor Server application, I want to redirect the user to the /Account/Login page automatically when the access token expires. Instead of implementing refresh token logic, I prefer to end the session and force the user to log in again.

    How can I detect token expiration and trigger a redirect to the login page? For example, is there a recommended way in ABP to handle 401 responses from HTTP requests and redirect accordingly?

    Is there a built-in mechanism in ABP for this use case?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You can use IntrospectAccessToken, which will check the access token, and redirect to the login page when it is invalid

  • User Avatar
    0
    yunusemrecaglar created

    Hi, The options.IntrospectAccessToken(); line is already present, but the redirect to the login page still doesn't happen when the token is invalid.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you share the full logs.txt file?

    liming.ma@volosoft.com

    Thanks.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Have you refreshed the web page during the token lifetime?

    Thanks

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you change the cookies' ExpireTimeSpan to 50 minutes and set CloseOnAuthenticationExpiration to true?

  • User Avatar
    0
    yunusemrecaglar created

    I’m using Blazor Server and my project is targeting .NET 7. Currently, I’m getting the error shown in the attached screenshot.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Please share your Blazor Server module class code.

    liming.ma@volosoft.com

    Thanks

  • User Avatar
    0
    yunusemrecaglar created

    Hi, I’ve shared the requested Blazor Server module class via email.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Try this in your module.

    PostConfigure<HttpConnectionDispatcherOptions>(x =>
    {
        x.CloseOnAuthenticationExpiration = true;
    });
    

  • User Avatar
    0
    yunusemrecaglar created

    Unfortunately, I’m still getting the same error.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Hi

    Can you share a project and steps to reproduce the problem?

    Thanks

  • User Avatar
    0
    yunusemrecaglar created

    In the project, I log in and navigate to any page. After waiting for a certain period of time, when I try to perform an action like a list search or call any GET method again, I receive an error at the bottom saying 'An unhandled exception has occurred. See browser dev tools for details. Reload'. The error description shows a 401 error.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Thanks. I will test it .

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I tested in the latest Blazor Server template project. And it works.

    Can you share your project or a demo project to reproduce?

    Thanks

  • User Avatar
    0
    yunusemrecaglar created

    The system is currently live. If you’d like, I can show you the issue via Zoom.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    I need to check the code. Please share a project. Thank you.

  • User Avatar
    0
    yunusemrecaglar created

    I’m unable to share the full project at this time, and unfortunately, we don’t have a demo available either. How do you suggest we proceed?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you try to use PreConfigure?

    PreConfigure<HttpConnectionDispatcherOptions>(x =>
    {
        x.CloseOnAuthenticationExpiration = true;
    });
    

    You can also output the AuthenticateResult?.Properties?.ExpiresUtc to logs by adding a custom middleware after UseAuthentication

    app.UseAuthentication();
    
    app.Use(async (httpContext, next) =>
    {
        var logger = httpContext.RequestServices.GetRequiredService<ILogger<YourModule>>();
        
        var authenticateResultFeature = context.Features.Get<IAuthenticateResultFeature>();
        if (authenticateResultFeature is not null)
        {
            logger.LogError("ExpiresUtc: " +  authenticateResultFeature.AuthenticateResult?.Properties?.ExpiresUtc);
        }
        else
        {
            logger.LogError("authenticateResultFeature is null");
        }
        await next(httpContext);
    });
    

    Thanks.

  • User Avatar
    0
    yunusemrecaglar created

    I've added the code you mentioned. Should I send the log file?

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Yes, Please share the new logs.

    Thanks.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Thanks. Can you also set the SlidingExpiration to false

    .AddCookie("Cookies", options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromDays(365);
        options.SlidingExpiration = false;
        options.IntrospectAccessToken();
    })
                
    

    And set .MinimumLevel.Debug() in Program.cs

    var loggerConfiguration = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
        .Enrich.FromLogContext()
        .WriteTo.Async(c => c.File("Logs/logs.txt"))
    

    Thanks again.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    What is your current Cookie and AccessToken lifetime(minutes)?

    Can you test your case in a version 7.2.2 template project?

    If you can reproduce, you can share it.

    Thanks.

Learn More, Pay Less
33% OFF
All Trainings!
Get Your Deal
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v10.1.0-preview. Updated on December 25, 2025, 06:16
1
ABP Assistant
🔐 You need to be logged in to use the chatbot. Please log in first.