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

Fetch Access Token from ProtectedStorage and Inject into HTTP Request Pipeline

$
0
0

I am encountering difficulties in integrating a JWT token, retrieved from ProtectedSessionStorage in a Blazor Server project (.NET 8), into the HTTP request pipeline for authorization. I've provided relevant code snippets below:

PersistentAuthenticationStateProvider

public async override Task<AuthenticationState> GetAuthenticationStateAsync(){   TokenProvider tokenProvider = await GetTokenProvide();   if (string.IsNullOrWhiteSpace(tokenProvider.AccessToken))   {      return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));   }   AuthenticationState? state = new(new ClaimsPrincipal(new    ClaimsIdentity(GetClaimsFromJwt(tokenProvider.AccessToken), "jwt")));   AuthenticationStateUser = state.User;   return state;}

I am using refit for my http calls I tried calling the ProtectedSessionstorage on each request with refit settings

public RefitService(IHttpClientFactory http, ProtectedSessionStorage sessionStorage){    _client = http.CreateClient(HTTP_CLIENT_KEY);    _sessionStorage = sessionStorage;    _refitSettings = new(new NewtonsoftJsonContentSerializer())    {       AuthorizationHeaderValueGetter =  (request, cancellationToken) =>       {           TokenProvider tokenProvider = GetTokenProvide().GetAwaiter().GetResult();           string? acessToken = tokenProvider.AccessToken;           return Task.FromResult(acessToken!);       }    }}

I also tried with Delegate Handler

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){    string? token = _tokenProvider.AccessToken;    if (!string.IsNullOrEmpty(token)) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer ", token);    HttpResponseMessage? response = await base.SendAsync(request, cancellationToken);    return response;}

Despite these attempts, I am unable to successfully pass the token to the HttpClient request pipeline. Any insights or suggestions on resolving this issue would be greatly appreciated.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



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