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