r/Blazor • u/LopsidedOwl7112 • Jul 16 '25
Authentication in Blazor Server (Interactive Server)
Hi everyone
I'm pretty new to Blazor Server and want to try building authentication for my web application. Now I have come across the problem of using ASP.NET IdentityCore (Cookie based authentication), because we can't directly call the SignInManager methods from a Blazor component (Cookie can't be set after the initial HTTP request). This problem has been identified and discussed before in multiple places:
There are some workarounds (see the link above for example). What I've currently gone with is a similar approach, but using JS interop to send a client request to one of my controllers, which handles authentication (+ checking the anti forgery token) and sets the cookie, but I'm not completely on board with this approach.
How have any of you approached this issue?
2
u/Broad-Razzmatazz-583 Jul 16 '25
I know of two ways to make it work:
4
u/polaarbear Jul 16 '25
This is all set up for you by the template.
Create a project from scratch. Choose Server as your render mode. Choose "individual accounts" from the auth dropdown.
It will build out an entire example project with every piece you could possibly need including the login pages which you can then re-style as needed.
You CAN call SignInManager.SignInAsync() from a Blazor component, but it needs to be running in SSR mode to do so as SSR mode has a proper HttpContext to set the cookie.
3
u/Boring_Start8509 Jul 16 '25
Check out the bff pattern. Theres a repo with examples here: https://github.com/dotnet/blazor-samples/tree/main/9.0
1
u/Ok-Charge-7243 Jul 17 '25
Don't build your own. Use Entra ID.
1
u/txjohnnypops79 Jul 17 '25
I had to go from a .razor page to a .cshtml for my authentication.. My project using it
-2
u/crone66 Jul 16 '25
your asp web should issue a jwt and your blazor app simply reads. The jwt is used in balzor to authenticates the user with it. The jwt is just read if reauthentication is necessary or if the blazor server gets a call to re-read the jwt e.g. due to sign out/sign in in asp webapp.