Share via


Getting Started with Authentication and Authorization using Blazor Server Side

Introduction 

The wait is over and yes now we can add the ASP.NET Core the Authentication and Authorization functions to Blazor application.

 In this article, we will see in detail on how to use Authentication and Authorization using Blzor ServerSide application, Yes now you can directly use the Authentication and Authorization for Blazor Server Side application. The new preview version of .NET Core 3.0 and Latest Visual Studio 2019 allows us to use the ASP.NET Identity to work with Blazor application.

Here, we will see how to,

  • Create Database in SQL server and use it for ASP.NET Table creations.
  • Display menu based on Authenticated and Authorized 

For non-authenticated and authorized members display different menu

ASP.NET Identity allows us to add login functionality to our system. Here, in this demo, we will be using SQL Server to store the user details and profile data. We will use ASP.NET Identity for new user registration, login, and to maintain the user profile data. If we talk about the login, the important part is whether the logged in user is authenticated and also authorized to view the pages.

Authentication and Authorization

Authentication

Check for the Valid User. Here, the question is how to check whether a user is valid or not. When a user comes to a website for the first time, he/she will register for that website. All their information, like username, password, email, and so on will be stored in the website database. When a user enters his/her userID and password, the information will be checked with the database. If the user has entered the same userID and Password as in the database, then he or she is a valid user and will be redirected to the website's home page. If the user entered UserID or Password that does not match the database, then the login page will give a message, something like “Enter valid Username or Password”. The entire process of checking whether the user is valid or not for accessing the website is called Authentication. 

Authorization

Once the user is authenticated, they need to be redirected to the appropriate page by his/her role. For example, when an Admin is logged in, they need to be redirected to the Admin Page. If an Accountant is logged in, then he/she needs to be redirected to his Accounts page.

Prerequisites

Make sure you have installed all the prerequisites in your computer. If not, then download and install them all, one by one.

Code part  

 Step 1: Create a Database

Firstly, we will create a Database and set the connection string in the appsettings.json file for DefaultConnection with our new database connection. We will be using this database for ASP.NET Core Identity table creation.

Create Database: Run the following script to create our database. 

USE MASTER   
GO   
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'BlazorDB' )   
DROP DATABASE BlazorDB   
GO   
     
CREATE DATABASE BlazorDB   
GO   
     
USE BlazorDB   
GO

Step 2 - Create an Blazor Server Side

After installing all the prerequisites listed above and ASP.NET Core Blazor extension, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project. 

Click on ASP.NET Core Web Application and click "Next".

Enter your project name and click the "Create" button.

 Now, we can see that for ASP.NET Core 3.0 has been listed. We Select the Blazor (Server Side) and then we click on Change Authentication to set our Authentication for our project.

Here we select the Individual User Account to store all our User details to SQL server.

After creating ASP.NET Core Blazor application, wait for a few seconds. You will see the below structure in the Solution Explorer.Here we can see pages folder which contains all our razor pages and Shared folder which is similar to our ASP.NET MVC shared folder which will contain the Navigation Menu page, MainLayout page for the content display and login display page which will be used for new user register and login to the site .appsetting.json page is to set our DB connection string.

Updating appsettings.json 

In appsettings.json  file we can find the DefaultConnection Connection string. Here in connection string change your SQL Server Name, UID and PWD to create and store all user details in one database.

Step 3: Register and Create your First User

Now our Blazor web application is ready for users to register in our website and also users can log in to our system after registration. Build and run your application to register your first user.

Click on the Register link to register our first User.

Migration

 When we click on the Register button we can see the below page. Don’t panic with this page as for the first time we run it we need to do the Migration, just click on the Apply Migrations button. 

We can see the confirmation as Migration Applied and then click on the Try refreshing the page message.


Refresh the Database

When we refresh our database, we can see all the Identity tables have been created.

Step 4: Displaying Menu by Authentication

Now let’s see how to show the menu for the non-authenticated user and Authenticated users.For this first, we add an razor page and named it as Userpage like below. 

Right click on the Pages folder and click add new Pages.

Name it as Usepage and click add.

In the page, we just add an H1 tag and some text as you are not Logged in.

Hide and show menu by Authentication

 Now we will show and hide the menu by user authentication and authorization. For doing this first we open the menu page. You can see NavMenu.razor under Shared folder.

Now we can see as by default 3 menu has been added as Home, Counter and Fetch data. We will show the Counter and Fetch data menu only for the Authenticated and Authorized users.

 And for non-authorized users, we will show our newly created Userpage. For this here we will be using the code like below.

<AuthorizeView> 
            <Authorized> 
                <li class="nav-item px-3"> 
                    <NavLink class="nav-link" href="counter"> 
                        <span class="oi oi-plus" aria-hidden="true"></span> Counter 
                    </NavLink> 
                </li> 
                <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="nav-item px-3"> 
                    <NavLink class="nav-link" href="NonUser"> 
                        <span class="oi oi-list-rich" aria-hidden="true"></span> Non Authoraized Menu 
                    </NavLink> 
                </li> 
            </NotAuthorized> 
        </AuthorizeView>

Here we can see as we have used the <Authorizeview> tag, This tag is used to check for the user is authorized or not. Inside the < Authorizeview> tag we used the <Authorized> tag for checking the user is Authorized and display the message, same like that use<NotAuthorized> tag to display for not authorized users. Here we show and hide the menus based on Authorized and NotAuthorized.

Conclusion

  
Firstly, create a sample BalzorDB Database in your SQL Server. In the appsettings.json file, change the DefaultConnection connection string with your SQL Server Connections. Here we have used our needed database to store all the ASP.NET identity information,by this way we can also create our other needed tables in the database and make relation to store user ids in needed tables.

See Also

Download

Getting Started with Authentication and Authorization using Blazor Server Side