Blazor Authentication and Authorization


Authentication and Authorization in Blazor can be broken down into 2 parts, the normal ASP.Net Core authentication and authorization, token based, cookies, Active directory and even 3rd party.  The Blazor specific authentication and authorization that is focused on managing the UI based on whether the   user is logged in, what roles and policies need to be applied.  We will be looking at the Blazor side.

To get started we will be creating a Blazor Server project and changing the authentication to Individual Accounts:


Once we have the project created, we need to run the command to create the data store for the user accounts:

     PM> Update-Database

Run the application and create a user account with a password.  For our application we used:
           1.       User Name: BlaozrAuth@everywherec.com       
           2.       Password: Pa33word!

Since we let Asp.Net handle creating everything we needed to manage the users, we are now ready to add our code to secure our application.

To look at how authentication and authorization works in Blazor we will add some code to the index page so we can see how to access the user information.

Code to Add:

       1.       Inject the Authentication service

@inject AuthenticationStateProvider AuthenticationStateProvider

        2.       Button to check is the user is logged in

      <button @onclick="@LogUsername">Check Auth Status</button>

        3.       A label to see the user’s authentication status

<p><strong>@userAuthStatus</strong></p>

        4.       Button on click on the method

               private async Task LogUsername()
              {
                  var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
                  var user = authState.User;

                  if (user.Identity.IsAuthenticated)
                 {
                      userAuthStatus =  $"{user.Identity.Name} is authenticated.";
                 } 
                 else
                { 
                     userAuthStatus = "User is not authenticated.";
                }
             }

This method allows us to get the status of the user and display weather they are logged in or not.  The AuthenticationStateProvider is the main service that handles the authentication state.  In this handler we are getting the current state and the user.  The we are checking if the user is authenticated (logged in) and set the status for the label.

That is how we can manually access the service to check on the current users.  In addition, there are a couple of built in Blazor components that will help us secure or UI.

We want to secure the entire Counter page so only users that are log in can access it.  To do this we just need to add the authorized attribute:

@attribute [Authorize]

You can add roles and policies with the attribute as well

@attribute [Authorize(Roles(“manager”)]

This will prevent any user that is not logged in or does not have the role/policy, if used from access the page.  If they try will received a “Not Authorized” message.  The out of the box message is not that pretty but you can change it.
Once you log in, you can now access the Counter page without any limitations.

So, what if you what to limit part of a page or part of the navigation based on whether the user is logged in or if the user has the right role/policy.  Blazor has a component for that, you use the “AuthorizedView” component. 

        <AuthorizeView>
            <Authorized>
                <li class="nav-item px-3">
                    <NavLink class="nav-link" href="fetchdata">
                        <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
                    </NavLink>
                </li>
            </Authorized>
            <NotAuthorized>
                <li class="disabled">
                    <NavLink class="nav-link" href="#">
                        <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
                    </NavLink>
                </li>
            </NotAuthorized>
        </AuthorizeView>

This will not display that part of the page unless the user meets the security requirements, logged in, role/policy.   Use the Authorized attribute to give access to everyone and use the NotAuthorized attribute to limit to non authorized users.

Just like the authorized attribute, you can use Role and Policy with the AuthorizedView to provide even more protection.

We have seen that Blazor has several ways that we can secure the UI whether it is a whole page or just a part of a page.  Combine this with the power of ASP.Net Core security and you have a good secure base to build on.





Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor - Cool Blur Loading Page