-
Notifications
You must be signed in to change notification settings - Fork 10k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refresh token during http request in Blazor Interactive Server with OIDC #55213
Comments
I recommend looking at the https://github.com/dotnet/blazor-samples/tree/bf387b3a9acafad1f5d9b8403c918b3548f81906/8.0/BlazorWebAppOidcBff sample. If the issue is that a server rather than the client interactive session is outlasting the access token in the cookie, I think you might need some JS code that pings the server using You could copy the logic from |
To clarify, I'm using Blazor Server with interactive rendering, not WebAssembly.
I'm fine with refreshing tokens in delegating handler, but the issue persists - the cookie can't be refreshed. Therefore, it will only function until the first complete page reload. This issue, is an edge case where the server's interactive session outlasts the access token's expiration, I'll likely have to live with it. However, I'm open to implementing new solutions if they become available in the future :) |
I'm currently using Blazor InteractiveServer where I connect to my external/existing API. Authentication part is SSR as in standard tempaltes, so the cookie with BearerToken is saved in the browser and is extracted with DelegatingHandler for each HttpClient call to that API. Any guidance or help is appreciated. |
@vukasinpetrovic did you try the technique used here CookieOidcRefresher |
Well, I have not, I I've set the cookie lifetime to 1 hour. I hope that users won't maintain an interactive session for such a long duration. If they do, I've implemented exception handling to refresh the page. |
@arkiaconsulting Thank you for the guidance. I had a lot of work during the past weeks and only now got to get back at this topic. I examined that CookieRefresher and from what I understood, OnValidatePrincipal only gets executed on page refresh or loading some non-InteractiveServer pages. If I navigate through my ServerInteractive pages and functionality, it does not get executed. Also, I used standard httpContext.SignInAsync method to login my user and that automatically generates the cookie. But from what I saw in CookieOidcRefresher, they use validateContext.Properties.Get/StoreTokens, which does not seem to use same thing that SignInAsync sets. Am I missing something? EDIT 2: This is all in case my blazor app connects to external api, not when api is inside blazor server. For context, this is my login method private async Task HandleLogin()
{
try
{
var loginResponse = await ApiService.TwoFactorLoginAsync(Data);
if (loginResponse != null && !string.IsNullOrEmpty(loginResponse.AccessToken))
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, loginResponse.User.Id.ToString()),
new("AccessToken", loginResponse.AccessToken),
new("RefreshToken", loginResponse.RefreshToken)
};
// Add each role to claim
loginResponse.User.Roles.ToList().ForEach(r => claims.Add(new Claim(ClaimTypes.Role, r.Name)));
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
Navigation.NavigateTo("/");
}
}
// NavigationException has to occur in order for framework to execute SSR redirection, that's just how it works
catch (Exception e) when (e is not NavigationException)
{
errorMessage = e.Message;
} And this is my auth handler for http context that is used for all api calls public class ApiHttpAuthHandler : DelegatingHandler
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
public ApiHttpAuthHandler(AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
var token = user.FindFirst("AccessToken")?.Value;
if (!string.IsNullOrEmpty(token))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
}
return await base.SendAsync(request, cancellationToken);
}
} |
Is there an existing issue for this?
Is your feature request related to a problem? Please describe the problem.
In the Blazor Web App (Interactive server), the token refresh process occurs during the OnValidatePrincipal cookie event. This event is triggered if the access token is less than 5 minutes away from expiration. However, this event only executes during a complete page reload.
A potential issue arises when a user reloads the page 6 minutes prior to the access token's expiration. In this case, the OnValidatePrincipal event does not refresh the token. If the user continues to interact with the website without a full page reload, the token may expire after 6 minutes. Consequently, all subsequent API requests are rejected. The question is how to handle such a scenario.
Describe the solution you'd like
The common solution to this issue is to refresh the token during an HTTP request with a DelegatingHandler. However, in our scenario, we cannot override the cookie inside the DelegatingHandler. The expected behavior, therefore, is to be able to refresh tokens in the DelegatingHandler while storing them in cookies. If there's a way to override the cookie inside the DelegatingHandler that I'm not aware of, that could also be a potential solution.
Additional context
cc: @guardrex dotnet/blazor-samples#267
https://github.com/dotnet/blazor-samples/tree/main/8.0/BlazorWebAppOidc
The text was updated successfully, but these errors were encountered: