--- sidebar_position: 3 title: Authentication --- ASP.NET Core supports configuration and management of security in Blazor apps. Security scenarios differ between Blazor Server and Blazor WebAssembly apps. Because Blazor Server apps run on the server, permission checks can determine the following: * User interface options presented to a user (for example, menu entries available to a user). * Access rules for application areas and components. Blazor WebAssembly apps run on the client. Authorization is only used to determine which UI options to display. Because client-side controls can be modified or overridden by a user, a Blazor WebAssembly app can't enforce authorization access rules. For our examples we will use a small example project available [here](/DemoAuthentication.zip). ## Creating a client application We are going to create a client application to manage local authentication. Create a new Blazor WASM app. Install the `Microsoft.AspNetCore.Components.Authorization` package in version 5.0.13. ![required library](/img/authentication/nuget-Microsoft.AspNetCore.Components.Authorization.png) Or using the Package Manager console: `PM> Install-Package Microsoft.AspNetCore.Components.Authorization -Version 5.0.13` :::caution In Blazor WebAssembly apps, authentication checks can be skipped because all client-side code can be modified by users. This also applies to all client-side application technologies, including JavaScript SPA application frameworks or native applications for any operating system. ::: ## Models As usual, we need to create the model classes that would take various authentication parameters for login and registration of new users. We will create these classes in the `Models` folder. ```csharp title="Models/RegisterRequest.cs" public class RegisterRequest { [Required] public string Password { get; set; } [Required] [Compare(nameof(Password), ErrorMessage = "Passwords do not match!")] public string PasswordConfirm { get; set; } [Required] public string UserName { get; set; } } ``` ```csharp title="Models/LoginRequest.cs" public class LoginRequest { [Required] public string Password { get; set; } [Required] public string UserName { get; set; } } ``` ```csharp title="Models/CurrentUser.cs" public class CurrentUser { public Dictionary Claims { get; set; } public bool IsAuthenticated { get; set; } public string UserName { get; set; } } ``` ```csharp title="Models/AppUser.cs" public class AppUser { public string Password { get; set; } public List Roles { get; set; } public string UserName { get; set; } } ``` We now have classes to help persist authentication settings. ## Creating the authentication service We will now create our authentication service, this one will use a list of users in memory, only the user `Admin` will be defined by default. Add a new interface in the project. ```csharp title="Services/IAuthService.cs" public interface IAuthService { CurrentUser GetUser(string userName); void Login(LoginRequest loginRequest); void Register(RegisterRequest registerRequest); } ``` Let's add a concrete class and implement the previous interface. ```csharp title="Services/AuthService.cs" public class AuthService : IAuthService { private static readonly List CurrentUser; static AuthService() { CurrentUser = new List { new AppUser { UserName = "Admin", Password = "123456", Roles = new List { "admin" } } }; } public CurrentUser GetUser(string userName) { var user = CurrentUser.FirstOrDefault(w => w.UserName == userName); if (user == null) { throw new Exception("User name or password invalid !"); } var claims = new List(); claims.AddRange(user.Roles.Select(s => new Claim(ClaimTypes.Role, s))); return new CurrentUser { IsAuthenticated = true, UserName = user.UserName, Claims = claims.ToDictionary(c => c.Type, c => c.Value) }; } public void Login(LoginRequest loginRequest) { var user = CurrentUser.FirstOrDefault(w => w.UserName == loginRequest.UserName && w.Password == loginRequest.Password); if (user == null) { throw new Exception("User name or password invalid !"); } } public void Register(RegisterRequest registerRequest) { CurrentUser.Add(new AppUser { UserName = registerRequest.UserName, Password = registerRequest.Password, Roles = new List { "guest" } }); } } ``` ## Authentication State Provider As the name suggests, this class provides the authentication state of the user in Blazor Applications. `AuthenticationStateProvider` is an abstract class in the `Authorization` namespace. Blazor uses this class which will be inherited and replaced by us with a custom implementation to get user state. This state can come from session storage, cookies or local storage as in our case. Let's start by adding the Provider class to the `Services` folder. Let's call it `CustomStateProvider`. As mentioned, this class will inherit from the `AuthenticationStateProvider` class. ```csharp title="Services/CustomStateProvider.cs" public class CustomStateProvider : AuthenticationStateProvider { private readonly IAuthService _authService; private CurrentUser _currentUser; public CustomStateProvider(IAuthService authService) { this._authService = authService; } public override async Task GetAuthenticationStateAsync() { var identity = new ClaimsIdentity(); try { var userInfo = GetCurrentUser(); if (userInfo.IsAuthenticated) { var claims = new[] { new Claim(ClaimTypes.Name, _currentUser.UserName) }.Concat(_currentUser.Claims.Select(c => new Claim(c.Key, c.Value))); identity = new ClaimsIdentity(claims, "Server authentication"); } } catch (HttpRequestException ex) { Console.WriteLine("Request failed:" + ex); } return new AuthenticationState(new ClaimsPrincipal(identity)); } public async Task Login(LoginRequest loginParameters) { _authService.Login(loginParameters); // No error - Login the user var user = _authService.GetUser(loginParameters.UserName); _currentUser = user; NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public async Task Logout() { _currentUser = null; NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } public async Task Register(RegisterRequest registerParameters) { _authService.Register(registerParameters); // No error - Login the user var user = _authService.GetUser(registerParameters.UserName); _currentUser = user; NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } private CurrentUser GetCurrentUser() { if (_currentUser != null && _currentUser.IsAuthenticated) { return _currentUser; } return new CurrentUser(); } } ``` You can see that, by default, we manage to implement a `GetAuthenticationStateAsync` function. Now, this function is quite important because Blazor calls it very often to check the authentication status of the user in the application. Additionally, we will inject the `AuthService` service and the `CurrentUser` model to the constructor of this class. The idea behind this is that we will not directly use the service instance in the view (Razor components), rather we will inject the `CustomStateProvider` instance in our views which will in turn access the services. **Explanation** `GetAuthenticationStateAsync` - Get the current user from the service object. if the user is authenticated, we will add their claims to a list and create a claims identity. After that, we will return an authentication state with the required data. The other 3 methods are quite simple. We will simply call the required service methods. But here is one more thing I would like to explain. Now, with each connection, registration, disconnection, there is technically a change of state in the authentication. We need to notify the entire application that the user's state has changed. Therefore, we use a notify method and pass the current authentication state by calling `GetAuthenticationStateAsync`. Pretty logical, huh? Now, to enable these services and dependencies in the project, we need to register them in the IOC, right? To do this, navigate to the project's `Program.cs` and make the following additions. ```csharp {6-10} title="Program.cs" public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("#app"); builder.Services.AddOptions(); builder.Services.AddAuthorizationCore(); builder.Services.AddScoped(); builder.Services.AddScoped(s => s.GetRequiredService()); builder.Services.AddScoped(); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); await builder.Build().RunAsync(); } ``` Now let's work on adding the Razor components for the UI. Here we are going to add 2 components i.e. Login component and Register component. We will protect the entire application by making it secure. This means that only an authenticated user will be allowed to view page data. Thus, we will have a separate layout component for the login/registration components. Go to the `Shared` folder of the project. Here is where you should ideally add all shared Razor components. In our case, let's add a new Razor component and call it, `AuthLayout.razor`. ```html title="Shared/AuthLayout.razor" @inherits LayoutComponentBase
@Body
``` You can see it's a pretty basic html file with an inheritance tag. We won't focus on css/html. However, this layout component will act as a container that will hold the login and register component itself. ## Login Component ```html title="Pages/Authentication/Login.razor" @page "/login" @layout AuthLayout

Login

``` ```csharp title="Pages/Authentication/Login.razor.cs" public partial class Login { [Inject] public CustomStateProvider AuthStateProvider { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } private string error { get; set; } private LoginRequest loginRequest { get; set; } = new LoginRequest(); private async Task OnSubmit() { error = null; try { await AuthStateProvider.Login(loginRequest); NavigationManager.NavigateTo(""); } catch (Exception ex) { error = ex.Message; } } } ``` ## Register Component ```html title="Pages/Authentication/Register.razor" @page "/register" @layout AuthLayout

Register

``` ```csharp title="Pages/Authentication/Register.razor.cs" public partial class Register { [Inject] public CustomStateProvider AuthStateProvider { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } private string error { get; set; } private RegisterRequest registerRequest { get; set; } = new RegisterRequest(); private async Task OnSubmit() { error = null; try { await AuthStateProvider.Register(registerRequest); NavigationManager.NavigateTo(""); } catch (Exception ex) { error = ex.Message; } } } ``` ## Enable authentication Now we need to let Blazor know that authentication is enabled and we need to pass the `Authorize` attribute throughout the application. To do this, modify the main component, i.e. the `App.razor` component. ```html title="App.razor"

Sorry, there's nothing at this address.

``` ### What is `AuthorizeRoteView`? It is a combination of `AuthorizeView` and `RouteView`, so it shows the specific page but only to authorized users. ### What is `CascadingAuthenticationState`? This provides a cascading parameter to all descendant components. Let's add a logout button to the top navigation bar of the app to allow the user to logout as well as force redirect to the `Login` page if the user is not logged in. We will need to make changes to the `MainLayout.razor` component for this. ```html {11} title="Shared/MainLayout.razor" @inherits LayoutComponentBase
About
@Body
``` ```csharp title="Shared/MainLayout.razor.cs" public partial class MainLayout { [Inject] public CustomStateProvider AuthStateProvider { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } [CascadingParameter] private Task AuthenticationState { get; set; } protected override async Task OnParametersSetAsync() { if (!(await AuthenticationState).User.Identity.IsAuthenticated) { NavigationManager.NavigateTo("/login"); } } private async Task LogoutClick() { await AuthStateProvider.Logout(); NavigationManager.NavigateTo("/login"); } } ``` We want to display our username and these roles on the index page soon after we log in. Go to `Pages/Index.razor` and make the following changes. ```html title="Pages/Index.razor" @page "/"

Hello @context.User.Identity.Name !!

Welcome to Blazor Learner.

    @foreach (var claim in context.User.Claims) {
  • @claim.Type: @claim.Value
  • }

Loading ...

Authentication Failure!

You're not signed in.

``` You can see there's a bunch of unsolvable errors that probably indicate few things are undefined in the namespace or something. This is because we didn't import the new namespaces. To do this, navigate to `_Import.razor` and add these lines at the bottom. ```html title="_Imports.razor" @using Microsoft.AspNetCore.Components.Authorization ``` Similarly we want to create an administration page accessible only by users with the `admin` role. Create the `Pages/Admin.razor` page: ```html title="Pages/Admin.razor" @page "/admin"

Admin Page

``` We are going to put in our menu our new page: ```html {10-16} title="Shared/NavMenu.razor" ...
... ``` ## Concept: Composant AuthorizeView The `AuthorizeView` component displays UI content selectively, depending on whether the user is authorized or not. This approach is useful when you only need to display user data and don't need to use the user's identity in procedural logic. The component exposes a context variable of type `AuthenticationState`, which you can use to access information about the logged-in user: ```html

Hello, @context.User.Identity.Name!

You can only see this content if you're authenticated.

``` You can also provide different content for display if the user is not authorized: ```html

Hello, @context.User.Identity.Name!

You can only see this content if you're authorized.

Authentication Failure!

You're not signed in.

@code { private void SecureMethod() { ... } } ``` The content of the `` and `` tags can include arbitrary elements, such as other interactive components. A default event handler for an authorized element, such as the `SecureMethod` method of the `