Tuesday, 29 January 2019

Implementing Asp.Net Identity without using default identity tables in the MVC application:

This article is about to implement the authentication using Asp.Net Identity, without using default identity tables. See the bellow steps for more details:


Step 1: Install the following nuget packages in your MVC application:
1. Microsoft.AspNet.Identity.Core
2. Microsoft.AspNet.Identity.Owin
3. Microsoft.Owin
4. Microsoft.Owin.Host.SystemWeb
5. Microsoft.Owin.Security
6. Microsoft.Owin.Security.Cookies
7. Microsoft.Owin.Security.OAuth
8. System.Security.Cryptography.Algorithms
9. System.Security.Cryptography.Csp
10. System.Security.Cryptography.Primitives

Step 2: Add new class named "Startup.cs" in the root of your application. Now paste the following code:

[assembly: OwinStartupAttribute(typeof(FastCash.Startup))]
namespace YOUR_NAMESPACE
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login"),

            });
            ConfigureAuth(app);
        }
    }
}

Step 3: Add new class named "Startup.Auth" under "App_Start" folder. Make sure you have set this class as partial using the partial keyboard. Now Paste the following code:

using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace YOUR_NAMESPACE
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }
}

Step 4: Start implementation in Login function of your controller like bellow:

[HttpPost]
public ActionResult Login(LoginModel model)
{
var options = new AuthenticationProperties();
options.AllowRefresh = true;
options.IsPersistent = true;
// options.ExpiresUtc = DateTime.UtcNow.AddSeconds(int.Parse(token.expires_in));
var claims = new[]
{
new Claim(ClaimTypes.Name, model.Email),
new Claim(ClaimTypes.Role, "admin"),
new Claim(ClaimTypes.Role,"SuperAdmin")
};
var identity = new ClaimsIdentity(claims, "ApplicationCookie");
Request.GetOwinContext().Authentication.SignIn(options, identity);

return RedirectToAction("Index", "Home");
}

Step 5: In previous step we have successfully logged-in the user with 2 roles "Admin" and "SuperAdmin". Now time to check authentication process. For this add an "Authorize" attribute on the Action that you want to secure like bellow code:

[Authorize(Roles = "SuperAdmin")]
public ActionResult Index()
{
  return View();
}

Now you are all set. Go ahead and add other logged-in data into claims, that you want to use throughout the application.

No comments:

Post a Comment