Skip to content

azade1490/AuthCookieBase

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Implementing Authentication & Authorization ๐Ÿ” in Blazor Server Without Identity

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.


๐Ÿ›ก Security Advantages

  • 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.


๐Ÿ›ธ Important Note

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 an EditForm component for handling the login form submission.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published