I have a Blazor WebAssembly application with cookie authentication configured. In particular, this is the cookie configuration:
builder.Services.ConfigureApplicationCookie(options =>{ options.LoginPath = "/login"; options.ReturnUrlParameter = "redirectUrl"; options.LogoutPath = "/api/logout"; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.SlidingExpiration = true; options.Events.OnRedirectToLogin = context => { context.Response.Redirect(context.Options.LoginPath +"?redirectUrl=" + context.Request.Path); return Task.CompletedTask; };});Now, when the cookie expires I want to send the user back to the login page and have them re-enter their credentials. I thought that setting the OnRedirectToLogin handler would have been enough to ensure any failed request due to an expired token was redirected to the appropriate login page. However that wasn't the case, and I detected two "unpleasant" behaviors:
When I call an API via, say,
GetFromJsonAsync<>, the server correctly redirects the call to the appropriate page, but then the client tries to deserialize it (the page's HTML code) and fails, displaying the Blazor error banner. It makes sense, in a way, but it's still a pain.When I open a page with an
[Authorize]attribute, the redirect isn't done at all and I can see the page as if I was still logged in. No errors appear on the console either. I guess Blazor doesn't check whether the cookie is still valid when I navigate to a different page, maybe because it's not programmed to care about what authentication scheme I use and therefore doesn't "know" to check the cookie, as long as I don't tell it to refresh the authentication state. Again, it makes sense, but it's a pain.
So... how exactly am I supposed to do this? I can't send the user back to the login as soon as they navigate to a page and I can't send them there when they make a call to the server, unless I handle the response deserialization and status code management by myself (which I would very much like to avoid, since it would mean replacing a lot of code). So when do I do it and how?
I'm using Blazor WebAssembly, .NET Core hosted, over .NET 7.0.
Thank you!