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, which is 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 licence covers ASP.Net, which is written in the.Net programming languages. ASP.NET is a web development platform that includes a programming interface, a powerful software infrastructure, and a number of services for creating robust web applications for both 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 use ASP.NET Core Identity. As a result, MongoDB will replace SQL Server as the Identity Database.
If you are interested in this ASP.NET, you can use ASP.NET Online Training and 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 sign-on/sign-out and access control for applications. OpenID Connect is used by IdentityServer to verify client identity, and the OAuth 2.0 framework is used to authorize 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. But on the other hand, ASP.NET Core Identity is a framework for managing users, passcodes, profiles, responsibilities, claims, tokens, email confirmation, and much more. 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 Question & 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 be implemented to allow users to authenticate themselves to secure areas of the website.
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 really look something like this:
The MongoDB database will be called “Identity” and will be accessible at localhost: 27017.
Next, in the app’s Settings folder, create a class called MongoDbConfig.cs. The MongoDB settings in the configuration file would be inhabited to this class, as previously stated. 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 with in 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, throughout your Package Manager Console, run the below command 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, make a new class called ApplicationUser.cs. Our app’s Identity User class will be this class. The above class’s code is provided below.
There are two things to keep in mind here:
This class will be mapped to MongoDB’s “Users” collection, according to Attriube [CollectionName(“Users”)].
The use of 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. To add the MongoDB implementation of Identity, we use the AddMongoDbStores method of the AspNetCore.Identity.MongoDbCore package Below is the highlighted code:
MongoDB installation:
You could perhaps install MongoDB Community Server on your system and afterward connect to your MongoDB database using the host and port values defined in the appsettings.json file.
I’ll be using Docker to run MongoDB in this tutorial. 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 Docker 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. The data from the form will be transferred from the View to the Controller using this class. 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, make a controller to add Identity Users to the database.
In the function Object() { [native code] }, the “UserManager” class of type “ApplicationUser” is injected into the controller. In the database, the Create action method 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 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. In your case, the port will be different.
You will be given a form to fill out in order 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 now has the ability to 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. In order 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 talk about how authentication works before I create 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 logs in by entering his credentials and clicking the log in button.
The user will be redirected to the secured controller and shown the secured information after a successful login.
Next, add two actions to the controller: “Login” and “Logout.”
Login
Logout
We’ll also need to make a Login.cshtml file, which will serve as the Login action’s Razor View. Place this file in the Accounts Views folder in order to sign in to the application; the user must fill in the Email and Password text boxes in the login view. Add the Logout action to the controller last but not least. This action has the [Authorize] attribute because it can only be initiated by logged in users.
Conclusion:
The above examples, along with 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.
Author Bio
I am Korra Shailaja, Working as a Digital Marketing professional & Content writer in MindMajix Online Training. I Have good experience in handling technical content writing and aspire to learn new things to grow professionally. I am an expert in delivering content on the market demanding technologies like Mulesoft Training, Dell Boomi Tutorial, Elasticsearch Course, Fortinet Course, PostgreSQL Training, Splunk, Success Factor, Denodo, etc.