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 Membership system 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:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Home/Login";

        });
You need to add the above code before the services.AddMvc() 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 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. You do this by adding the below code line:

app.UseAuthentication();
Note: Call the UseAuthentication method before calling UseMvcWithDefaultRoute orUseMvc.

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 Login and Logout features. With Login feature users can log in themselves to the application (i.e. authenticate themselves to the application).

Through 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 an Authenticated user.
[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 next.

Home Controller Code

Add the Login Action method which has the following code:
[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 there is a check to find out if the Username and Passwords of the user are both ‘Admin’.

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

if ((username == "Admin") && (password == "Admin"))
{
//…
}
Next, to Authenticate the user and create a cookie 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 ‘/Secured/Index’). Since you are not authenticated therefore you will be redirected to the Login View.

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 View and click the button.

Note that as soon as the user is authenticated a Cookie by the name of 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
Next, add the Logout action method that contains the following code:
[HttpPost]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync();
    return RedirectToAction("Index");
}

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

Testing Logout Feature

Click the logout button of the Index Action of the Secured Controller(URL – ‘/Secured’). 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 *