Share via

Token is coming as null from GetTokenAsync in Blazor Server

Buddhi - BLUE LOTUS 360 1 Reputation point
2022-05-22T15:34:02.667+00:00

I have created a blazor server app(.NET6) and I have used JWT authentication to authenticate the app with referring this Microsoft document . when going to get a token that is saved in the local storage, I'm getting a null value.

my program.cs

var builder = WebApplication.CreateBuilder(args);
                       ...

            builder.Services.AddRazorPages();
            builder.Services.AddServerSideBlazor();
            builder.Services.AddHttpContextAccessor();
            builder.Services.AddScoped<TokenProvider>();
            builder.Services.AddHttpClient();


            builder.Services.AddAuthentication(options =>
                         {
                             options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                             options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                             options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                         })
                        .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
                         {
                             x.RequireHttpsMetadata = false;
                             x.SaveToken = true;
                         });


   if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    ...
    app.UseHttpsRedirection();

    app.UseStaticFiles();

    app.UseRouting();

    app.MapBlazorHub();
    app.MapFallbackToPage("/_Host");

    app.Run();

TokenProvider.cs

public class TokenProvider
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
}

InitialApplicationState.cs

public class InitialApplicationState
{
    public string AccessToken { get; set; }
    public string RefreshToken { get; set; }
}

Pages/_Host.cshtml file ,

@using Microsoft.AspNetCore.Authentication

...

@{
    var tokens = new InitialApplicationState
    {
        AccessToken = await HttpContext.GetTokenAsync("access_token"),
        RefreshToken = await HttpContext.GetTokenAsync("refresh_token")
    };
}

<component type="typeof(App)" param-InitialState="tokens" 
    render-mode="ServerPrerendered" />

I am getting this AccessToken and RefreshToken as null above code

App.razor

@inject TokenProvider TokenProvider

...

@code {
    [Parameter]
    public InitialApplicationState InitialState { get; set; }

    protected override Task OnInitializedAsync()
    {
        TokenProvider.AccessToken = InitialState.AccessToken;
        TokenProvider.RefreshToken = InitialState.RefreshToken;

        return base.OnInitializedAsync();
    }
}

in here I am setting tokenprovider token values, but it is being set as null values, because of InitialState tokens are null so I need to know why does this happen??,where I am wrong?? please help me

Developer technologies | .NET | Blazor

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,061 Reputation points
    2022-05-22T16:10:24.753+00:00

    How are you sending the jwt token to your server? They are typically used with webapi.

    As blazor server is a single request to create a signal/r hub, there is only one request to authenticate and this is a web flow login via razor pages.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/?view=aspnetcore-6.0&tabs=visual-studio

    I suspect you are using blazor WASM documentation, which would use jwt tokens to make api calls.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.