Getting Started With Authentication And Authorization Using Blazor Server Side

The wait is over and yes, now we can add the ASP.NET Core Authentication and Authorization functions to the Blazor application. In this article, we will see in detail how to use Authentication and Authorization using the Blazor Server-Side application. Now, you can directly use the Authentication and Authorization for the Blazor Server Side application. The new preview version of .NET Core 3.0 and the latest Visual Studio 2019 allow us to use the ASP.NET identity to work with a Blazor application.

Here, we will see,

  • Create a database in SQL Server and use it for ASP.NET table creation.
  • Display a menu to authenticated and authorized members

ASP.NET table

For non-authenticated and authorized members, display a different menu.

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, and 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 a Valid User. Here, the question is how to check if 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 user ID and password, the information will be checked with the database. If the user has entered the same user 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 enters a 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, then needs 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 on your computer. If not, then download and install them all, one by one.

Prerequisites

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 exists 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

After running the DB Script we can see that the Database has been created and tables have not yet been created.

DB Script

Step 2. Create a Blazor server-side.

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

Visual Studio 2019

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

Next

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

Create button

Now, we can see that 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.

ASP.NET Core 3.0

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

SQL server

After creating the ASP.NET Core Blazor application, wait for a few seconds. You will see the below structure in the Solution Explorer. Here, we can see the pages folder which contains all our razor pages and the 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 the LoginDisplay page which will be used for the new user register and login to the site .appsetting.json page is to set our database connection string.

ASP.NET MVC

Updating appsettings.json

Json

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

Default connection

Step 3. Register and create your first User.

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

Blazor web application

Click on the Register link to register our first User.

Register link

Migration

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

Migration

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

Migration Applied

Refresh the page and we can see the newly registered user has been logged in to our website.

Registered user

We can also update the user details by clicking on the user name at the top of the site.

User details

Refresh the Database

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

Refresh the Database

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 a Razor page and name it as Userpage like below.

Right-click on the Pages folder and click "Add New Pages".

Add new pages

Name it as UsePage and click "Add".

UsePage

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

H1 tag

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.

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 Authorized Menu
            </NavLink>
        </li>
    </NotAuthorized>
</AuthorizeView>

Here we can see as we have used the <Authorizeview> tag. This tag is used to check if the user is authorized or not. Inside the < Authorizeview> tag we used the <Authorized> tag for checking if the user is Authorized and displayed the message, in the same way use <NotAuthorized> tag to display non-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. In this way, we can also create our other needed tables in the database and make relations to store user ids in needed tables.


Similar Articles