Authentication And Authorization In ASP.NET Core MVC Using Cookie

Authentication And Authorization In ASP.NET Core MVC Using Cookie
Authentication And Authorization In ASP.NET Core MVC Using Cookie

Authentication is the process of obtaining some sort of credentials the users and using those credentials to verify the user’s identity. There are three authentication we discuss one of them Type is for security like: password and pin.

Authorization is the process of allowing an authentication user to resources.

so, we have many techniques to validate to the user like: windows authentication, jwd authentication etc today we discuss about the implementation and making ASP.NET Core MVC applications more secure for the use.

ASP.NET also supports custom authentication providers. This simply means that you set the authentication mode for the application to none, then write your own custom code to perform authentication. For example, you might install an ISAPI filter in IIS that compares incoming requests to list of source IP addresses, and considers requests to be authenticated if they come from an acceptable address. In that case, you would set the authentication mode to none to prevent any of the .net authentication providers from being triggered.

The fig below illustrates the authorization and authentication mechanisms provided by ASP.NET and IIS.

Now the application in ASP.NET

Be careful that while creating the project, your template should be web application (controller) and change the authentication whereas: no Authentication: e.g like the user have the option that they are change the password.

We are choosing MVC template because we would like to see some Login and Logout functionality on UI along with Authentication and Authorization using Cookies. Now, click OK and it will take a few seconds and the project will be ready. Run it for checking if everything is working fine or not. Once everything is OK, you are ready to go.

Let us move to the starting point of the ASP.NET Core application file which is “Startup.cs” where we configure the setting for the application like configuring the required services and configuring the middleware services etc. So, implementing the Authentication features, first, we must add the authentication and then use it. So, let us move to Startup.cs ConfigureService method and add the authentication feature using the following line of code, it will be just above services.AddMvc().

app.UseAuthentication(); 

Following is the whole code for adding the Authentication and using it.

using Microsoft.AspNetCore.Authentication.Cookies; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Http; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 

namespace CookieDemo 
{ 
    public class Startup 
    { 
        public Startup(IConfiguration configuration) 
        { 
            Configuration = configuration; 
        } 

        public IConfiguration Configuration { get; } 

        // This method gets called by the runtime. Use this method to add services to the container. 
        public void ConfigureServices(IServiceCollection services) 
        { 
            services.Configure<CookiePolicyOptions>(options => 
            { 
                // This lambda determines whether user consent for non-essential cookies is needed for a given request. 

                options.CheckConsentNeeded = context => true; 

                options.MinimumSameSitePolicy = SameSiteMode.None; 

            }); 

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); 
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 
        } 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
        { 
            if (env.IsDevelopment()) 
            {  
                app.UseDeveloperExceptionPage(); 
            } 
            else 
            { 
                app.UseExceptionHandler(“/Home/Error”); 
            } 
            app.UseStaticFiles(); 
            app.UseCookiePolicy(); 
            app.UseAuthentication(); 
            app.UseMvc(routes => 
            { 
                routes.MapRoute( 
                    name: “default”, 
                    template: “{controller=Home}/{action=Index}/{id?}”); 
            }); 
        } 
    } 
} 

The first login method is rendering thr UI for login page and once fill the data required for login as username and password then the second action method as Login will work and send the Post request to the server.

First, we checked the weather of username and password should not be empty when we validate into the environment, we must fill correct information like username and password.

After  done this information if the information is correct so the system will be allowed to user to sing in into the environment  “SignInAsync” and if everything goes in the right direction then we redirect to the Home page.

Now  let`s create the login page from where we can give functionality user enter the id name and password. so right click on the login icon and view the home page in the environment.

FUNCTION:

@{ 
    ViewData[“Title”] = “Login”; 
} 
<div class=”container”> 
    <div class=”row”>         
        <div class=”col-md-3″> 
            <h2><strong>Login Page </strong></h2><br /> 
            <form asp-action=”login” method=”post”> 
                <div class=”form-group”> 
                    <label>Username</label> 
                    <input type=”text” class=”form-control” id=”userName” name=”userName” placeholder=”Enter username”> 
                </div> 
                <div class=”form-group”> 
                    <label>Password</label> 
                    <input type=”password” class=”form-control” name=”password” id=”password” placeholder=”Password”>  
                </div> 
                <div class=”form-check”> 
                    <button class=”btn btn-info” type=”reset”>Reset</button> 
                    <button type=”submit” class=”btn btn-primary”>Submit</button> 
                </div>  
            </form> 
        </div>
    </div> 
</div> 

Note:

Be sure you have cleared all cookies which have been  created based on your previous login. If you will not do this, you will be accessing the HOME page, it is because authenticated user cookie is available in browser memory.

So, let us open the Account Controller and add the following logout action method.

[HttpPost] 
public IActionResult Login(string userName, string password) 
{ 
    if (!string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password)) 
    { 
        return RedirectToAction(“Login”); 
    } 
    //Check the username and password 
    //Here can be implemented checking logic from the database 
    ClaimsIdentity identity = null; 

    bool isAuthenticated = false; 

    if (userName == “Admin” && password == “password”) 
    { 
        //Create the identity for the user 
        identity = new ClaimsIdentity(new[] { 
                    new Claim(ClaimTypes.Name, userName), 
                   new Claim(ClaimTypes.Role, “Admin”) 
                }, CookieAuthenticationDefaults.AuthenticationScheme); 
        isAuthenticated = true; 
    } 

    if (userName == “Mukesh” && password == “password”) 
    { 
        //Create the identity for the user 
        identity = new ClaimsIdentity(new[] { 
                    new Claim(ClaimTypes.Name, userName), 
                    new Claim(ClaimTypes.Role, “User”) 
                }, CookieAuthenticationDefaults.AuthenticationScheme); 
        isAuthenticated = true; 
    } 
    if (isAuthenticated) 
    { 
        var principal = new ClaimsPrincipal(identity); 

        var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); 

        return RedirectToAction(“Index”, “Home”); 
    } 
    return View(); 
} 

@{ 
    ViewData[“Title”] = “Setting Page”; 
} 

<div class=”container”> 
    <div class=”row”> 
        <div class=”col-md-12″> 
            <h2><strong>Setting Page </strong></h2><br /><br /> 
            Hello @User.Identity.Name !, Role @User.FindFirst(claim=>claim.Type==System.Security.Claims.ClaimTypes.Role)?Value 
            <a asp-action=”logout” asp-controller=”account”> 
                Logout 
            </a> 
            <br /> 
            <br /> 
            <h4>Admin role user can only access this page!!</h4> 
        </div> 
    </div> 
</div> 

NOW we have added everything, so it is time to run the function so just compile your program. After the run the program we can get the environment as blow given in the pic:

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

one + 8 =

You May Also Like