Create Identity In Simple Ways Using ASP.NET MVC 5

Introduction

This article explains about the basics of Identity, how to create identify, and uses of Identity, in a very simple way, using ASP.NET MVC5.

Identity in MVC 5

Identity is a secured way of authentication methods in web applications. It is used for identifying the authorized user.

Background

There are different ways of creating an Identity in applications, but this article explains how to create it using OWIN in ASP.NET MVC. OWIN is very helpful for creating the Identity for applications without writing a lot of code. Identity is used to find and allow the users to enter the application based on their authentication and authority. It does not allow anonymous users to enter the application.

Assembly

There are three important assemblies used for creating Identity. These assemblies help the programmer in developing the Identity without writing thousands of lines of code in ASP.NET MVC application. These important assemblies are:

  1. Microsoft.Asp.Net.Identiy.Core
  2. Microsoft.Asp.Net.Identiy.EntityFramework
  3. Microsoft.Asp.Net.Identiy.Owin
    Assembly

OWIN

ASP.NET MVC and ASP.NET Core support the Open Web Interface for .NET (OWIN). OWIN is an interface between .NET web applications and web servers. The main goal of the OWIN interface is to decouple the server and the applications. It acts as middleware.

ASP.NET MVC, and ASP.NET applications using middleware can interoperate with OWIN-based applications, servers, and middleware. It helps develop different types of authentication methods.

OWIN

OWIN helps Facebook, Google, and Microsoft Accounts, and Twitter authentications. It acts as a middleware for those authentication programs. The following diagram shows the assembly for Facebook, Google, Microsoft Accounts, and Twitter.

Microsoft Account

Steps for creating Identity in ASP.NET MVC

The following steps explain how to create Identity in ASP.NET web applications.

Step 1. Open a new project in Visual Studio and select Visual C#. In Visual C#, select ASP.NET Web Application and give the project name. Click OK.

Visual C#

Step 2. Select the MVC template from the template type and click the Change Authentication button.

MVC

Step 3. We can use different types of Authentication. Now, we are going to choose Inpidual User Accounts and click the OK button.

For applications that store user profiles in the SQL Server database, users can register or sign in using their existing accounts for Facebook, Twitter, Google, Microsoft, or another provider in Inpidual User Accounts.

Inpidual User Accounts

Step 4. After choosing the type of authentication, in your Controller, go back to the previous window and again click OK. It takes a few minutes to open the application. After that, click the OK button.

Application

Step 5. After opening the project, click “Startup. cs” in Solution Explore and we can see the starting page where OWIN assembly starts.

Code

Right-click on “ConfigureAuth(app)” and go to the definition page where we can see an auto-generated code.

Page

We can see different types of authentication in OWIN above the marked part of the image. When using OWIN Identity, the code is generated automatically. The developer does not have to write much code.

Step 6. Now, compile the application. If there are no errors, run the application. After running the application, we can see the “Register” and “Login” links on the top-right side of the application.

Register

Click the login link and give your credentials. Now, you can enter the application.

Step 7. If you are a new user, click the register link and register your username and password to enter the application.

Register link

If you are an existing user, click Login. You can enter directly using your credentials.

Local account

After Logging in successfully, we can see our username on the top-right side of our application.

Application Name

Step 8. We can use the Identity on any page in this application. We are going to enable Identity in one of the new pages in ASP.NET MVC applications.

Create a Controller in the View page and enable Identity using an attribute with the help of OWIN middleware.

After adding the Controller, we will be adding the following code in the “Test” Controller.

Code before enabling the Identity.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewIdentity.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Identity()
        {
            return Content("We are using Identity");
        }
        
        public ActionResult NonIdentity()
        {
            return Content("We are not using Identity");
        }
    }
}

It will not ask for any credentials while running the application using the following URL.

http://localhost:51868/Test/Identity

Because it does not use any attribute for enabling Identity, if you enable the Identity using an attribute, each time it will ask for the credentials. URL might differ for you based on your project Controller, View, and port number.

URL

Code after enabling the Identity.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewIdentity.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        /// <summary>
        /// Identity In Action Result Level
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Identity()
        {
            return Content("We are using Identity");
        }
        
        public ActionResult NonIdentiy()
        {
            return Content("We are not using Identity");
        }
    }
}

Using the “Authorize” attribute, one can enable the Identity. The above code explains how to enable Identity that enables Controller level or Action method level.

Identity in Controller Level

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewIdentity.Controllers
{
    /// <summary>
    /// Identity in Controller Level
    /// </summary>
    /// <returns></returns>
    [Authorize]
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Identity()
        {
            return Content("We are using Identity");
        }
        public ActionResult NonIdentiy()
        {
            return Content("We are not using Identity");
        }
    }
}

If you run the application, it will directly redirect to the login page because we have enabled the Identity. Now, run it using the “http://localhost:51868/Test/Identity” URL.

Login

After entering your credentials, it will redirect to your corresponding View and you can see the final page.

Localhost

If you do not need an identity for a particular Action method, we can disable it using the “AllowAnonymous” attribute. Now, run “http://localhost:51868/Test/NonIdentiy” URL does not redirect to the login page. It directly runs the given URL because we use the AllowAnonymous attribute.

Code For Anonymous

namespace NewIdentity.Controllers
{   
    [Authorize]
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Identity()
        {
            return Content("We are using Identity");
        }

        /// <summary>
        /// Disable identity to particular action result
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult NonIdentity()
        {
            return Content("We are not using Identity");
        }
    }
} 

Database in Identity

When we create Identity in ASP.NET MVC, the database connection is created automatically and stores your credentials. We can see the database connection in “Web. config” at the connectionString tag.

ASP.NET

Our db created a “.mdf” file in the App_Data folder. When we see the App_Data folder, we see no file. Go to Solution Explorer on the top of the right side, and click all files icon. After clicking the all files icon, we can see the “.mdf” file in App_Data.

See the screenshots below.

App_Data

App

We can see all tables in the database after expanding the database folder. Go to the menu bar, select View, and click Server Explorer.

Database

In Server Explorer, under the table folder, we can see all tables as well as View, Store Procedures, and other needed folders. The “AspNetUsers” table is the main table that stores our credentials.

Right-click on the AspNetUser table and click New Query, like the below screen.

Query

Now, write a select query and run it in the query window. Here, we can see all the credentials.

 Credentials

Database Connection

View pages connected to the database using Entity framework. ”IdentityConfig.cs” is mainly for identity, it is located inside of “App_Start” in Solution Explorer. All database coding is placed in IdentityConfig.cs. It is an auto-generated code. Inside of a marked line, the code is for connecting to the entity framework.

Data connection

Right-click on the ApplicationUser class and go to definition. Now, we can see the Web. config connection string name placed inside the ApplicationDbContext class. Here, we connect the database using the Web. config connection string.

User

Conclusion

This article helps to learn the basics of Identity in ASP.NET MVC.. The next part of the article will explain the role of Identity with users. I hope this article helps many developers.


Similar Articles