How to Implement Cookie Authentication in ASP.NET Core

How to Implement Cookie Authentication in ASP.NET Core

One of the easiest methods to implement your own Custom Authentication Logic in ASP.NET Core is with Cookie Authentication method. Note that the Cookie Authentication method is not related to ASP.NET Core Identity in any way.

Let me show how to Implement the Cookie Authentication in an ASP.NET Core application.

Configuration

First you need to configure the Cookie Authentication method. So open the Startup.cs class of your App and inside it’s ConfigureServices() method create the Authentication Middleware service with the AddAuthentication and AddCookie methods:
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Home/Login";

            });

    services.AddControllersWithViews();
}

You need to add the above code before the services.AddControllersWithViews() method.

In the above code I have passed the CookieAuthenticationDefaults.AuthenticationScheme to the AddAuthentication() method. It sets the default authentication scheme for the app.

This means when the login is successful then a cookie created for the authenticated user. This cookie will be named as .ASPNetCore.Cookies.
Also notice that I have set the Login View URL as the Login Action of the Home Controller:
options.LoginPath = "/Home/Login";

It means if an unauthenticated user tries to access secured URLs of the App then they will be automatically redirected to the /Home/Login URL, where they have to enter their username and password in order to authenticate themselves.

Next, go to the Configure() method and tell your App to use the authentication & authorization. You do this by adding the below 2 highlighted code lines.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
Note: Call the UseAuthentication & UseAuthorization() methods just after app.UseRouting().

Implement Cookie Authentication in the Application

Now I will show you how to use the Cookie Authentication in my ASP.NET Core Application. In this application first create 2 controllers which are described below:

1. HomeController.cs

In the Home Controller you will have the Login and Logout features. With Login feature users can log in themselves to the application (i.e. authenticate themselves to the application).

With the Logout feature users can perform their logout from the application.

2. SecuredController.cs

The Secured Controller can only be accessed by users who are logged in to the application. This controller will have the [Authorize] attribute.

Secured Controller Code

Create a controller called SecuredController.cs. Add [Authorize] attribute to it, so it makes all it’s Action methods to only be accessed by Authenticated users.
[Authorize]
public class SecuredController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
Next, create it’s Index view inside Views ➤ Secured folder with the following code:
<form method="post" asp-controller="Home" asp-action="Logout">
    <button class="btn btn-lg btn-primary btn-block">Logout</button>
</form>
This view has a form with a button. When the button is clicked then the Logout Action of the Home controller is invoked. I will explain the Logout feature in a moment.

The Login Feature

Add the Login Action method which has the following code. Here I am adding it to Home Controller.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace CA.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(string username, string password, string ReturnUrl)
        {
            if ((username == "Admin") && (password == "Admin"))
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username)
                };
                var claimsIdentity = new ClaimsIdentity(claims, "Login");

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
                return Redirect(ReturnUrl == null ? "/Secured" : ReturnUrl);
            }
            else
                return View();
        }
    }
}

Explanation: The Login Action takes username, password and the return URL in it’s parameter. First a check is done to find out if the Username and Passwords of the user are both Admin.

If both are Admin then only then the user is authenticated.

if ((username == "Admin") && (password == "Admin"))
{
//…
}
Next, to Authenticate the user and create a cookie for holding his information, construct a ClaimsPrincipal so that the user information is serialized and stored in the cookie. This is done by first creating ClaimsIdentity:
var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, username)
};
var claimsIdentity = new ClaimsIdentity(claims, "Login");

Then call the SignInAsync() method to sign-in the user. It takes 2 parameters which are:

  • a) Scheme which is CookieAuthenticationDefaults.AuthenticationScheme
  • b) Claims Principal

Check the below given code of SignInAsync() method:

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));
After the user is signed in, he is redirected to the return URL (which is given in the parameter):
return Redirect(ReturnUrl == null ? "/Secured" : ReturnUrl);

Now, create the Login View inside the Views ➤ Home folder with the following code:

<form method="post">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button>Sign in</button>
</form>

The View has a form that contains 2 input controls for letting the user to put and submit his username and password.

Testing Authentication Feature

Run your application and visit the URL of the Secured Controller’s Index Action method (this URL is https://localhost:44339/Secured). Since you are not authenticated therefore you will be redirected to the Login Page.

See the below video which explains this feature:

cookie authentication working
Cookie Authentication working video

Now enter Admin for both username and password fields in the Login page and click the button. This time you will be taken to the Secured Page.

Note that as soon as the user is authenticated a Cookie by the name of .ASPNetCore.Cookies is created and stored in the browser. You can see this cookie inside the Application area of the browser’s ‘Developer Tools’, as shown by the below image:

cookie stored in the browser

The expiry time of the Cookie can be set by using the ConfigureApplicationCookie method of IServiceCollection interface.

The below code added to the ConfigureServices() method of the Startup class sets the expiry time to 10 minutes in sliding expiry way.

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = ".AspNetCore.Cookies";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
    options.SlidingExpiration = true;
});

The Logout Feature

Next, add the Logout action method that contains the following code:
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace CA.Controllers
{
    public class HomeController : Controller
    {
        // ...

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }
    }
}

To perform the logout of the current user just call the SignOutAsync() method. This method removes the Cookie from the browser.

Testing Logout Feature

Click the logout button after you did the login procedure. This will logout the user and the Cookie will be deleted from the browser (check the Application’s tab of the browser).

The link to download the full source code of this tutorial is given below:

Download

Conclusion

The Cookie Authentication is a great way to quickly implement custom Authentication method in your website.

If you want a more professional approach then implement Identity Membership in your website, check How to Setup and Configure Identity Membership System in ASP.NET Core .

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

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