Authentication in Blazor

By Syncfusion®, Inc. · Last updated

Find out who the user is: cookies and their security options, cookies in Blazor, the cookie authentication scheme and claims, ASP.NET Core Identity, password hashing with salt, register, login and logout, AuthenticationStateProvider, cascading authentication state and ClaimsPrincipal.

What you will learn

  • Explain cookies and set HttpOnly, Secure, SameSite and expiry
  • Describe the cookie scheme, claims and ASP.NET Core Identity
  • Explain how passwords are stored and how login and logout work
  • Read the current user with AuthenticationStateProvider and cascading state

Authentication Overview

  • Authentication means finding out who the user is. Logging in is authentication.
  • The user proves it with credentials: something only they know or have, like an email and a password.
  • Authorization is the next step: deciding what that user may do. You learn it in the next lesson.
  • HTTP forgets everything between requests. So after login, the server gives the browser a small ticket, and the browser shows it with every request. In ASP.NET Core, that ticket is a cookie.

Real-World Example:

Ravi logs in to the Tea Shop with his email and password. The server checks them and hands back a login cookie. From then on, every page he opens sends the cookie, so the server knows it is Ravi and shows his orders.

Animation: 1. The browser sends an email and a password to the server. 2. The server checks them and answers with a login cookie. 3. Every later request carries the cookie, and the server answers: Hello, Ravi.

Browser

Server checks the password

1. log in: email + password

2. here is your login cookie

3. GET /orders + cookie: "It is Ravi"

Log in once, get a cookie, and show it with every request.

Cookies

What Cookies Are

  • A cookie is a small piece of named text that a website asks the browser to keep, like theme=dark.
  • The server sets it with a Set-Cookie header on a response. (A header is an extra line of information on a request or response.)
  • After that, the browser sends it back by itself, in a Cookie header, with every request to the same site.
  • Cookies are used for login, remembering choices (language, theme) and shopping carts.

Two steps. First, the server answers a request with the header Set-Cookie: theme=dark, and the browser stores it in its cookie jar. Second, on the next request the browser adds the header Cookie: theme=dark by itself.

Browser

cookie jar theme=dark

Server

1. response: Set-Cookie: theme=dark

2. next request: Cookie: theme=dark

The server sets a cookie once. The browser sends it back every time.

Managing Cookies

On the server, the current request (HttpContext, see Middleware Pipeline) gives you three things:

JobCode
Set (create or change)context.Response.Cookies.Append("theme", "dark", options)
Readcontext.Request.Cookies["theme"] (null if it is not there)
Deletecontext.Response.Cookies.Delete("theme")
  • Deleting really means "tell the browser it has expired", so the browser throws it away.
  • You can see a site's cookies in the browser: press F12, open Application (Chrome, Edge) or Storage (Firefox), then Cookies.

In the below example, the page sets, reads and deletes a real theme cookie in your browser. The small cookies.js file does the cookie work, and C# calls it with JS interop (see JavaScript Interop).

Cookie Security Options

A login cookie is like a house key, so it must be protected. Each cookie can carry these options:

OptionWhat it doesProtects against
HttpOnlyJavaScript cannot read the cookieBad scripts that steal cookies
SecureSent only over HTTPSPeople reading the network
SameSiteNot sent when another site starts the request (Lax or Strict)Fake requests from other sites
Expires / Max-AgeWhen the browser throws it awayLogins that last forever

One Set-Cookie header split into labelled parts: the name and value .AspNetCore.Cookies=CfDJ8..., then expires (when it ends), secure (HTTPS only), samesite=lax (not from other sites) and httponly (hidden from JavaScript).

Set-Cookie: .AspNetCore.Cookies=CfDJ8...; expires=...; secure; samesite=lax; httponly

name = value the ticket itself

expires when it ends

secure HTTPS only

samesite=lax not from other sites

httponly no JavaScript

The options travel with the cookie in the Set-Cookie header.

On the server, you set them with CookieOptions:

  • Without Expires, the cookie is a session cookie: it goes away when the browser is closed.
  • The login cookie that ASP.NET Core makes is already HttpOnly, Secure and SameSite=Lax.

In the below example, a promo cookie gets a Max-Age of 5 seconds. Click the button and watch the browser throw it away.

The demo cookies here are not HttpOnly, because JavaScript has to read them. Never keep login tickets or other secrets in a cookie that JavaScript can read.

Using Cookies in Blazor

Where your code runs decides how it can reach cookies:

WhereHow
Static server rendering (no interactivity)Read and set cookies through HttpContext, which the page gets as a [CascadingParameter]
Interactive (Server or WebAssembly)There is no HttpContext per click. Use JS interop for non-HttpOnly cookies, as in the boxes above
LoginLet ASP.NET Core make and read the login cookie for you (next section)

In the below code, a static page reads the theme cookie from the request:

  • This page has no @rendermode, so it runs as a static page and HttpContext is set.
  • In an interactive component, HttpContext is null. Do not rely on it there.

Cookie Authentication

Cookie Authentication Scheme

  • An authentication scheme is a named way to find out who the user is. The cookie scheme is named "Cookies".
  • With it, ASP.NET Core does the cookie work for you. After login, it writes one encrypted login cookie (scrambled, so nobody can read or change it). On each request, it reads the cookie back and knows the user.
  • Inside the cookie is the user, described by claims.

Three new words describe a user in .NET:

WordMeaningExample
ClaimOne fact about the userName = Ravi, Email = ravi@teashop.com
ClaimsIdentityThe claims plus how the user was checked (the scheme)claims + "Cookies"
ClaimsPrincipalThe user: holds the identitywhat your code reads as User

In the below example, Ravi is built from three claims. An identity counts as logged in only when it has a scheme name: here, "Cookies".

  • Remove , "Cookies" and run it again: Logged in turns False.
  • ClaimTypes.Name is a long, standard name (a web address). Split('/').Last() only shortens it for display.

This is how you turn on the cookie scheme in Program.cs, and how a login page makes the cookie with SignInAsync:

  • The login page must be a static page (no @rendermode), like the forms in Server Rendering. A cookie can only be set on an HTTP response, and interactive clicks have none.
  • HttpContext.SignOutAsync(...) deletes the cookie again: that is logout.

ASP.NET Core Identity

Writing users, passwords and login pages yourself is a lot of careful work. ASP.NET Core Identity is the built-in membership system (everything about user accounts). It gives you:

  • A users table in your database (with EF Core, see Database Handling).
  • Safe password storage, account lockout after many wrong tries, email confirmation and two-factor login.
  • Ready-made Blazor pages: Register, Login, Logout, Manage account.
  • The cookie scheme, set up for you.

The easiest start is a new app with Individual Accounts (-au Individual):

Click Next to see each command.

The template adds these parts:

PartIts job
Data/ApplicationUser.csYour user class. It inherits IdentityUser (email, password hash, and more)
Data/ApplicationDbContext.csThe EF Core database with the Identity tables
Components/Account/Pages/Register, Login, Manage and the other account pages
UserManager<ApplicationUser>Creates and finds users, checks passwords
SignInManager<ApplicationUser>Logs users in and out (makes and deletes the cookie)

And it registers Identity in Program.cs:

Password Storage

  • Never store passwords as they are. If the database is stolen, every password is known at once.
  • Store a hash instead: a one-way scramble. You can turn a password into a hash, but not a hash back into the password.
  • Add a salt first: a random value, different for every user. Then two users with the same password still get different hashes.
  • To check a login, hash the typed password with the same salt and compare the two hashes.

The password chai123 and a random salt go into PBKDF2, which mixes them 100,000 times. Out comes a hash. The database stores only the salt and the hash, never the password.

"chai123"

salt random bytes

PBKDF2 mixes 100,000 times

Database stores salt hash: siP+kso5qxqX... no password

Password plus salt goes in; only the salt and the hash are stored.

  • PBKDF2 is a hashing method made slow on purpose, so an attacker cannot try billions of passwords quickly.
  • Identity does all this for you: its PasswordHasher uses PBKDF2 with SHA-512 and 100,000 rounds, and stores the salt and hash together in the PasswordHash column.

In the below example, you hash a password the same way (with fewer rounds, to stay fast in the browser). Click Hash it twice and compare: same password, new salt, different hash. Then click Check.

  • Change the box to tea999, click Hash it, then Check: "Wrong password".
  • FixedTimeEquals compares in the same time whether the hashes match early or late, so timing gives nothing away.

Do not write your own password code in a real app. Use Identity, which hashes, salts, checks and upgrades passwords for you.

Register, Login, and Logout

These are the three steps every account goes through. In the Identity template:

Three rows. Register: the form calls UserManager.CreateAsync, which saves the user with a password hash in the database. Login: the form calls SignInManager.PasswordSignInAsync, which checks the hash and writes the login cookie. Logout: a form posts to Account/Logout, which calls SignInManager.SignOutAsync and deletes the cookie.

Register

UserManager.CreateAsync

user + hash saved

Login

SignInManager.PasswordSignInAsync

cookie written

Logout

SignInManager.SignOutAsync

cookie deleted

Register saves the user. Login writes the cookie. Logout deletes it.

The key lines from the template's pages:

  • RememberMe decides whether the cookie has an end date (it survives a browser restart) or is a session cookie.
  • Logout is a form that posts to Account/Logout. That endpoint calls SignInManager.SignOutAsync(), which deletes the cookie. <AntiforgeryToken /> stops other sites from logging your users out.

Authentication State

The login cookie lives on the server side of the request. Your components need an easy way to ask "who is the user?". In Blazor, that is the authentication state.

AuthenticationStateProvider

  • AuthenticationStateProvider is the service that answers "who is the user?".
  • Its method GetAuthenticationStateAsync() returns an AuthenticationState. Its User property is the ClaimsPrincipal you met above.
  • When the user changes (login, logout), the provider calls NotifyAuthenticationStateChanged, so the components can update.
  • In the Identity template, the provider is IdentityRevalidatingAuthenticationStateProvider. It reads the user from the login cookie and checks every 30 minutes that the account still exists.

In the code boxes there is no login cookie. So TeaShopAuthStateProvider is a pretend provider: its LogIn and LogOut methods change the user directly. A real app registers its provider in Program.cs. The code boxes do that for you:

In the below example, the page injects the provider and asks it who the user is. Click Who am I?, then log in and ask again.

Cascading Authentication State

  • Asking the provider in every component is repetitive, and the page does not update by itself after login.
  • Cascading authentication state hands the state down to every component, like the cascading values in Components.
  • Turn it on once in Program.cs with builder.Services.AddCascadingAuthenticationState(); (the Identity template already has it). You can also wrap a part of the page in <CascadingAuthenticationState>.
  • A component receives it as a [CascadingParameter] Task<AuthenticationState>. It is a Task, so you await it.
  • When the provider says the user changed, every component gets the new state and renders again.

Animation: the AuthenticationStateProvider at the top feeds CascadingAuthenticationState. From there, the Task of AuthenticationState flows down to three components, NavMenu, OrdersPage and UserBadge, which each receive it as a cascading parameter.

AuthenticationStateProvider

CascadingAuthenticationState

NavMenu

OrdersPage

UserBadge

Task<AuthenticationState>

One provider, one cascade, and every component below it knows the user.

In the below example, UserBadge has no buttons and no injected service. It only receives the cascading state, yet it updates when you log in or out.

  • OnParametersSetAsync runs again each time the cascading value changes, so the text stays up to date.
  • With AddCascadingAuthenticationState() in Program.cs, you do not need the <CascadingAuthenticationState> tag. The code boxes use the tag because they have no Program.cs of their own.

Showing or hiding things by login state only changes the screen. Real protection, such as blocking a page or an API for strangers, is authorization: the next lesson.

Accessing the Current User (ClaimsPrincipal)

Once you have the AuthenticationState, its User is a ClaimsPrincipal. These are the members you use most:

CodeGives you
User.Identity?.IsAuthenticatedtrue when someone is logged in
User.Identity?.NameThe name claim, for example Ravi
User.FindFirst(ClaimTypes.Email)?.ValueThe value of one claim, or null
User.IsInRole("Staff")true when the user has that role claim
User.ClaimsAll claims, to loop over

In the below example, the provider logs in a user with a name, an email and a role. UserCard reads them from the cascading state. Try both buttons.

  • Meena has the role claim Staff, so IsInRole("Staff") is True. The next lesson uses roles like this to decide who may open which page.
  • In C# code outside components (for example in an API endpoint), the same user is HttpContext.User.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Saving passwords as plain text, or with a fast hash like SHA-256 onlyA hash is a hashUse Identity's PasswordHasher (PBKDF2 with salt)Stolen databases reveal passwords
A login cookie without HttpOnly or SecureDefault options are fine everywhereKeep HttpOnly, Secure and SameSite onScripts or the network can steal the login
new ClaimsIdentity(claims) with no schemeHaving claims means logged inPass the scheme: new ClaimsIdentity(claims, "Cookies")IsAuthenticated is false
Calling SignInAsync from an interactive componentAny button can set a cookieLog in from a static page or an endpoint"Headers are read-only" or no cookie at all
Using HttpContext in interactive componentsIt is always thereUse the authentication state insteadHttpContext is null, so the code crashes
Forgetting AddCascadingAuthenticationState()Components find the user by themselvesAdd it in Program.cs (or wrap with <CascadingAuthenticationState>)The cascading Task<AuthenticationState> is null

Check Yourself

Exercises

What to Remember

  • Authentication finds out who the user is. After login, a cookie carries the proof with every request.
  • A cookie is named text the browser keeps and sends back. Set it with Response.Cookies.Append, read it with Request.Cookies[...], delete it with Response.Cookies.Delete.
  • Protect cookies with HttpOnly, Secure, SameSite and an expiry.
  • The cookie scheme writes an encrypted login cookie with SignInAsync and removes it with SignOutAsync. The user is a ClaimsPrincipal made of claims.
  • ASP.NET Core Identity gives you users, safe password hashing (salt + PBKDF2) and the Register, Login and Logout pages. Start with dotnet new blazor -au Individual.
  • Components get the user from AuthenticationStateProvider, or better, from the cascading Task<AuthenticationState> (AddCascadingAuthenticationState()).
  • Read the user with Identity.IsAuthenticated, Identity.Name, FindFirst(...) and IsInRole(...).

Next: Authorization