Asp.Net Core Identity With Mongodb As Database {Detailed}

For many of us, building a website or doing anything related to web development is a tough prospect. Designers can easily create and design a customized software platform using the leading web development platforms and tools. There is a platform called ASP.Net, an open-source web application framework developed by Microsoft for web development. The server-side application assists in the creation of dynamic web pages. The Apache license covers ASP.Net, which is written in the.Net programming languages. ASP.NET is a web development platform with a programming interface, a powerful software infrastructure, and several services for creating robust web applications for PCs and mobile devices.

Table of contents:

  • Introduction
  • IdentityServer meaning
  • ASP.NET Core Identity vs. IdentityServer
  • MongoDB Identity Configuration
  • MongoDB installation
  • Creating MongoDB Identity Users
  • MongoDB Identity Roles Creation
  • ASP.NET Core Identity in MongoDB User Authentication
  • Conclusion

Introduction:

ASP.NET is built on top of the HTTP protocol, and it uses HTTP commands and policies to establish bidirectional coordination and interaction between the browser and the server. Similarly, if we talk about databases for storing mongodb is a good example. In this walkthrough, we’ll use MongoDB as the database and ASP.NET Core Identity. As a result, MongoDB will replace SQL Server as the Identity Database.

If you are interested in ASP.NET, you can take ASP.NET Online Training, join the course, and improve your skills in this field.

What do you mean by IdentityServer exactly?

IdentityServer is a central Authentication Server that allows application sign-on/sign-out and access control. IdentityServer uses OpenID Connect to verify client identity, and the OAuth 2.0 framework authorizes resources to authenticate clients. Clients receive JWT tokens from IdentityServer, which they use to identify themselves on secured endpoints.

Standardizing the authentication service is a great idea because it eliminates the need to define authentication logic for each application. The IdentityServer will centralize access control, ensuring that every application is protected. Features of IdenttityServer include:

  • Service of Authentication
  • API Federation Gateway for external identity providers such as Azure Active
  • Directory and other social media Sign-on/Sign-out Access Control

ASP.NET Core Identity vs. IdentityServer:

IdentityServer uses OAuth 2.0, and OpenID Connect continues providing authentication services using JWT tokens. However, ASP.NET Core Identity is a framework for managing users, passcodes, profiles, responsibilities, claims, tokens, email confirmation, etc. IdentityServer and Identity are both used in conjunction to create highly secure systems.

To Focus your future bright in ASP.NET. Crack ASP.NET Interview Questions & Answers.

We’ll start by configuring Identity to use MongoDB as the database, and then we’ll create an example project with Identity Users and Roles. Finally, a Login and Logout feature would allow users to authenticate themselves to secure website areas.

MongoDB Identity Configuration:

Create a new IdentityMongo ASP.NET Core (MVC) application.

The database name, host, and port values would now be added to the “appsettings.json” file. Such values will then be populated into a Startup.cs C# class. The appsettings.json file should look something like this:

The MongoDB database will be called “Identity” and accessible at localhost: 27017.

Next, create a class called MongoDbConfig.cs in the app‘s Settings folder. As previously stated, this class will inhabit the MongoDB settings in the configuration file. The code in MongoDbConfig.cs should look such as this one:

Now import the following namespace into Startup.cs:

Subsequently, as seen in the code below, populate the database settings from appsettings.js to MongoDbConfig.cs within the ConfigureServices method.

Identity in AspNetCore. The MongoDbCore package provides a MongoDb UserStore and RoleStore adapter for ASP.NET Core Identity, allowing you to use MongoDB instead of SQL. So, run the below command throughout your Package Manager Console to add the above package to your app.

MongoDB, as a NoSQL database, has never had tables or columns; instead, it uses Collections. Identity User and Role classes will be created and mapped to these collections.

Our Identity User and Role classes will now be defined. The Identity User class would be derived from MongoIdentityUser and mapped to the “Users” collections. The Identity Role class will be derived from MongoIdentityRole and plotted to the “Roles” collections.

Within the Models folder, create a new class called ApplicationUser.cs. This will be our app’s Identity User class. The code for the above class is provided below.

There are two things to keep in mind here:

This class will be mapped to MongoDB’s “Users” collection, according to Attribute [CollectionName(“Users”)].

Using Guid for the T type in MongoIdentityUser indicates that the collection’s primary key will be a Guid type.

The final step is to add ASP.NET Core Identity to the Startup class’s ConfigureServices method.

Import the ApplicationUser and ApplicationRole classes’ namespaces.

Register Identity to use these classes for users and roles using IdentityMongo.Models. We use the AddMongoDbStores method of the AspNetCore to add the MongoDB implementation of Identity.Identity.MongoDbCore package Below is the highlighted code:

MongoDB installation:

You could perhaps install MongoDB Community Server on your system and connect to your MongoDB database using the host and port values defined in the appsettings.json file.

In this tutorial, I’ll use Docker to run MongoDB. Creating the first ASP.NET Core App in a Docker Container is the first tutorial in the ASP.NET Core Docker series, which I recently finished. If you want to learn more about Docker, my series will be “extremely useful.”

MongoDB can be run from Docker in two steps:

Docker Desktop should be installed on your computer.

Create a container and use it to run MongoDB.

At around this point, our database is up and running. Installing the MongoDB Tools visual studio extension allows us to view the MongoDB database and its Collections.

Creating MongoDB Identity Users:

Let’s get started on adding Identity Users as a feature. So, inside the “Models” folder, make a class called User.cs. Using this class, the data from the form will be transferred from the View to the Controller. We will have a form in the view where we can fill out the details of a user, and the application will create the Identity User after we submit the form.

The User.cs code can be found here. It only has three fields: Name, Email, and Password, all of which have validation attributes.

After that, a controller will be made to add Identity Users to the database.

In the function Object() { [native code] }, the “UserManager” class of type “ApplicationUser” is injected into the controller. The Create action method in the database simply creates a new Identity User. The CreateAsync method of the UserManager performs the task of creating the user.

The View simply displays a form for adding an Identity User to the MongoDB database. After that, it’s time to put the theory into practice. In Visual Studio, open the app and navigate to https://localhost:44323/Operations/Create. The port will be different in your case.

You will be given a form to fill out to create a user. Fill in the blanks with the following information:

John is his name.

john@johnosting.com

Admin@123 is the password.

Mongo Explorer can confirm that this user has been created in the MongoDB database.

MongoDB Identity Roles Creation:

MongoDB can now create Identity Roles. In the Controller’s function Object() { [native code] }, we must inject the RoleManager class of type ApplicationRole. Then, using RoleManager’s CreateAsync method, we can create the Roles. Add a new action method called CreateRole to the OperationsController.cs file and make the changes I’ve highlighted in the code.

Let’s check the database for the Role. Connect to the database again in Mongo Explorer, and you’ll notice that “Roles” collections have been added. The “Admin” role can be found in the Roles collections.

ASP.NET Core Identity in MongoDB User Authentication:

Anonymous user access to secure areas of the website must be prevented. To accomplish this, we must include authentication and authorization middleware in our ASP.NET Core application. After UseRouting, open the Startup class Configure method and add these two middlewares. Next, create a new controller in your project called SecuredController.cs and secure it from anonymous user access by using the [Authorize] attribute.

The controller has only one action, “Index.” The authenticated user’s Claims and Properties will be displayed in the Index view. As a result, place this index view in the Views Operations folder. I’d like to discuss how authentication works before creating the Login feature. When an anonymous user attempts to access the Secured Controller, the following occurs:

The user will be taken to the Login page.

The user enters his credentials and clicks the log-in button.

After a successful login, the user will be redirected to the secured controller and shown the secured information.

Next, add two actions to the controller: “Login” and “Logout.”

Login

Logout

We’ll also need to create a Login.cs html file will serve as the Login action’s Razor View. To sign in to the application, place this file in the Accounts Views folder; the user must fill in the Email and Password text boxes in the login view. Last but not least, add the Logout action to the controller. This action has the [Authorize] attribute because only logged-in users can initiate it.

Conclusion:

The above examples and the code will undoubtedly assist you in comprehending ASP.NET Core Identity with MongoDB as the database. We used the MongoDB database for the Identity database to store the users and roles. We also created a login and logout feature, after which we authenticated users and their roles with secured controllers. ASP.NET is used to create interactive, data-driven web applications over the internet. It has a lot of controls for putting together, configuring, and attempting to manipulate code to make HTML pages, such as text boxes, buttons, and labels.