seeking assistance to reflect JWT-based authentication and authorization from the API Project to a Blazor WEb APP project #62652
Unanswered
Aboubakar2
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm working on a .NET 9 Blazor Web App (the new hybrid model supporting both SSR and WASM). On the backend, I have a separate ASP.NET Core Web API secured with JWT tokens. On the client side, the Blazor app authenticates users by calling the API, receives a JWT, stores it in localStorage, and attaches it to API requests via the Authorization: Bearer header. I also have a custom AuthenticationStateProvider that reads the token and exposes the user's claims.
This setup works well for rendering authenticated UI using , checking roles, and so on.
However, I want to use the [Authorize] attribute on .razor pages to restrict access at the routing level. As soon as I add [Authorize] to a page, I get this runtime error:
InvalidOperationException: Unable to find the required 'IAuthenticationService' service.
Please add all the required services by calling 'IServiceCollection.AddAuthentication'
I understand that [Authorize] in Blazor Web App SSR mode relies on proper server-side authentication via AddAuthentication() and that it doesn't work if the server can't validate or recognize the user identity. Since I'm only storing the token in localStorage and not sending it in cookies or headers for SSR, the server has no idea who the user is.
I'm trying to figure out if there’s a clean way to support [Authorize] on pages while keeping my existing JWT-based client-side auth flow. I would like to avoid switching to cookie-based auth or duplicating logic.
So my questions are:
Is there a way to make [Authorize] work in a Blazor Web App using only JWT stored in localStorage?
If not, what is the best practice for securing pages (not just content blocks) with a JWT-only setup?
Would sending the token to the server via a custom cookie or header and validating it manually be a viable workaround?
Or what is the best way to reflect that authentication and Authorization with JWT that i have on the API project in the Blazor WEB APP???
Any guidance would be appreciated. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions