When the authentication logic is implemented in the backend, Identity should not directly access the databas โ this helps maintain a clean separation of responsibilities and consistent application logic.
๐ง We know that Identity internally uses
HttpContext.SignInAsync();to sign in the user.
๐ Therefore, we can call this method directly ourselves โ just like Identity does.
๐ Hereโs what happens:
๐ It creates an authentication cookie that stores user claims.
๐ The authentication middleware takes care of validating the cookie, keeping our code clean and simple.
๐ We only need to add this line at the top of any protected page:
@attribute [Authorize]This attribute automatically checks the userโs permissions based on the authentication cookie. If the user doesnโt have access, theyโll be redirected to the AccessDenied page.
๐ You can also use the built-in <AuthorizeView> component in the UI to conditionally show content based on user roles or permissions.
- Using
@attribute [Authorize]prevents unauthorized users from even rendering the page, improving security. - Since the cookie is created on the server side and has
HttpOnly = true
๐ JavaScript or any malicious script cannot read it, making it resistant to XSS attacks. ChatGPT said:
๐Because SameSite=Lax, the cookie is sent only with "safe" requests (such as GET).
๐ ASP.NET Core also includes built-in Anti-Forgery protection, keeping the cookie safe from CSRF attacks.
Because HttpContext can only be modified in static server-side rendering (static SSR) pages โ not in interactive (Blazor Server) ones โ
you should not specify a rendermode for the login page, so it defaults to static SSR.
โ ๏ธ Note: Since static SSR pages are not interactive and events donโt work there, you must use anEditFormcomponent for handling the login form submission.