Create Identity In Simple Ways Using ASP.NET MVC 5

Datetime:2016-08-23 04:37:32          Topic: ASP.NET MVC           Share

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.

Definition

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

OWIN

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

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

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

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.

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

Step 3

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

For applications that store user profiles in SQL Server database, users can register or sign in using their existing accounts for Facebook, Twitter, Google, Microsoft, or another provider in Individual 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 OK button.

Step 5

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

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

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

Step 6

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

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

Step 7

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

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

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

Step 8

We can use the Identity in 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 View page and enable Identity using attribute with the help of OWIN middleware.

After adding Controller, we will be adding the following code in “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 NonIdentiy()  
        {  
            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 attribute, each time it will ask for the credentials. URL might differ for you based on your project Controller, View and port number.

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 “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 Contoller 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 login page because we have enabled the Identity. Now, run it using “http://localhost:51868/Test/Identity” URL. 

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

If you do not need identity for particular Action method, we can disable using “AllowAnonymous” attribute. Now, run “http://localhost:51868/Test/NonIdentiy” URL does not redirect to login page. It directly runs the given URL because we use 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 particuler action result  
        /// </summary>  
        /// <returns></returns>  
        [AllowAnonymous]  
        public ActionResult NonIdentiy()  
        {  
            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 connectionString tag.

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

See the screenshots below:

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

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

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

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

Database Connection

View pages connected to 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 auto-generated code. Inside of marked line, the code is for connecting to the entity framework.

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

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.





About List