I’m stuck with this.
So I have a new .NET8 Blazor WebApp – Server Interactive. So this is only one Blazor project.
I am adding Auth0 authentication for it to communicate with my other API by Auth0 Access Token.
So it works like that, for example:
User clicks button -> HttpClient sends request to my WebApi -> Delegating handler checks the access token (reads from cookie) and refreshes it.
Now, I don’t have any idea how to tell the client: “Hey, you have new access token here – write it into a cookie”.
My delegating handler looks like that:
internal class AccessTokenRefreshHandler(IClientTokenStorage _clientTokenStorage,
ITokenRefreshService _tokenRefresher) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var accessToken = await _clientTokenStorage.ReadAccessToken();
AddAccessToken(accessToken, request);
var response = await base.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.Unauthorized)
{
var newTokens = await RefreshTokens();
AddAccessToken(newTokens.AccessToken, request);
return await base.SendAsync(request, cancellationToken);
}
else
return response;
}
private void AddAccessToken(string accessToken, HttpRequestMessage msg)
{
if (string.IsNullOrWhiteSpace(accessToken))
msg.Headers.Authorization = null;
else
msg.Headers.Authorization = new AuthenticationHeaderValue("Authorization", accessToken);
}
private async Task<RefreshedTokenInfo> RefreshTokens()
{
return await _tokenRefresher.RefreshTokens();
}
}
So it’s simple – take the access token, add to the header, if 401 then refresh the token.
Until that everythink works fine.
RefreshTokens
just gets another HttpClient and sends refresh request to Auth0. It gets new refresh and access tokens but then I am not able to store it.
I tried HttpContext
(from HttpContextAccessor) but there was this header exception (headers already sent).
I tried ILocalStorageService
, but got JS exception (JavaScript interop calls cannot be issued at this time).
So how can write new tokens to the client?
Should I create some SignalR
connection? Or maybe I could use the existing one? Or maybe I should refresh the token only on client side using some timer?
Or maybe there is some client-server shared storage that I could use?
Or maybe I am doing something completely bad?