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

how to access JWT in blazor server after login?

$
0
0

I'm calling an API for authentication from a Blazor server project. The API responds with JWT.

I'm able to save it after login in a ProtectedLocalStorage like this

await protectedLocalStorage.SetAsync("authToken", result.Data.Token);

And added a CustomAuthenticationStateProvider in order to read the token & add it to all requests'DefaultRequestHeaders like this

public override async Task<AuthenticationState> GetAuthenticationStateAsync(){ProtectedBrowserStorageResult<string> token;var anonymous = new ClaimsPrincipal(new ClaimsIdentity());try{    try    {        token = await _protectedBrowserStorage.GetAsync<string>("authToken");    }    catch    {        token = new();    }    if (!token.Success)    {        return new AuthenticationState(anonymous);    }httpClient.DefaultRequestHeaders.Authorization =                        new AuthenticationHeaderValue("Bearer", token.Replace("\"", ""));    var identity = new ClaimsIdentity(ParseClaimsFromJwt(token.Value), "jwt");    var user = new ClaimsPrincipal(identity);    return await Task.FromResult(new AuthenticationState(user));}catch (Exception exc){    return new AuthenticationState(anonymous);}}

And able to delete it for logout like this

await protectedLocalStorage.DeleteAsync("authToken");

I noticed that after login, GetAuthenticationStateAsync always gets called twice where the 1st time _protectedBrowserStorage is null& the 2nd time it has the correct value.

The problem is that when I go to any page after login, _protectedBrowserStorage comes as null in GetAuthenticationStateAsync

I need to know why after login GetAuthenticationStateAsync gets called twice. I assume the 1st time it's called, it's very early in Blazor lifecycle because I get this exception

JavaScript interop calls cannot be issued at this time

And the 2nd time it's called after Blazor is ready to access it.

More importantly, I need to know how to access the token for all the pages after the login. I know the token exists but I'm not able to access it


Viewing all articles
Browse latest Browse all 4839

Trending Articles



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