Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor AuthenticationStateProvider problem

$
0
0

I have a Blazor server-side app with a need to authenticate without SQL server.

My DI in Program.cs:

builder.Services.AddScoped<AuthenticationServer>();builder.Services.AddAuthorizationCore();builder.Services.AddScoped<TokenServerAuthenticationStateProvider>();builder.Services.AddScoped<AuthenticationStateProvider>(provider => provider.GetRequiredService<TokenServerAuthenticationStateProvider>());

My subclass of AuthenticationStateProvider:

public class TokenServerAuthenticationStateProvider : AuthenticationStateProvider{    public override async Task<AuthenticationState> GetAuthenticationStateAsync()    {        var token = await GetTokenAsync(); // gets the token        var claims = new List<Claim>() { new Claim(ClaimTypes.Name, Constants.WebClientUser) };        var identity = string.IsNullOrEmpty(token) ? new ClaimsIdentity() : new ClaimsIdentity(claims);        return new AuthenticationState(new ClaimsPrincipal(identity));                }    public async Task<string> GetTokenAsync() {  // gets token from local storage  }    public async Task SetTokenAsync(string token)    {        // code that stores the token in local storage here        NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());    }}

In my MainLayout.razor I have this split view for a login page or the app itself:

<CascadingAuthenticationState><AuthorizeView Policy=@Constants.WebClientUser><Authorized>                           @Body</Authorized><NotAuthorized><Login /></NotAuthorized></AuthorizeView></CascadingAuthenticationState>

In the Login.razor component I inject the AuthenticationStateProvider:

@inject TokenServerAuthenticationStateProvider tokenProvider

... in the same Login component, I have input elements for user, password and a button to login which calls a method DoLogin():

private async Task DoLogin(){    // authenticate user/password and get a valid token (works)    var token = await authServer.Login(_inputUsername, _inputPassword);    // use the custom auth state provider to set the token and call the code above    await tokenProvider.SetTokenAsync(token);    // reload the page    navManager.NavigateTo("/");}

However this doesn't work. I am always routed back to the login page and it never deems to be authorized to view the @body.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>