In this article, I will be showing a very simple example of how to set up cookie authentication.
Configuration
- Create the project (with defaults selected)
2. Add services to Program.cs
- The AddCascadingAuthenticationState() service takes care of providing authentication state across ALL render modes.
3. Change the route view component in Routes.razor to AuthorizeRouteView.
Testing
- Create a login page.
I made a simple form that checks if credentials match "Harry" and "Potter". This page needs to be a static server rendered page.
If you notice in the below code, we now have access to the HttpContext variable. This is only available as a cascading parameter in static server rendered components/pages.
2. Add the authorize attribute to the home page.
- Now, if you navigate to the home page, it will redirect you to the login page since we setup the login path in Program.cs.
Accessing the User in interactive server components
There might be times you need to access the user's authentication state in interactive server components.
Note: The HttpContext property is only available on static-server rendered components. It will be null in interactive components.
If you just need the authentication state for display purposes, you can just use the <AuthorizeView> component but if you need to access the state in the code block you can create a cascading parameter as usual.
I included a simple example below. I placed this in the Counter page since it has its render mode set to InteractiveServer.
Result:
And there it is. I tried to keep it as simple and basic as possible. I hope this helped anyone out there creating new Blazor apps in .NET 8!