Thursday, December 3, 2026
HomeC#Cookie Authentication in ASP.NET Core ~ IT Tutorials with Instance

Cookie Authentication in ASP.NET Core ~ IT Tutorials with Instance


On this article, we are going to study How one can implement Cookie Authentication in ASP.NET Core with out utilizing Identification. I’ll attempt to cowl each step in order that novices can simply perceive.

This text is the a part of ASP.NET Core studying collection. In case you are new to ASP.NET Core, then I’ll advocate you to undergo the earlier article of this collection:

Authentication is the method of verifying the id of the person.  On this article, we are going to authenticate the person by verifying the person’s credentials. I’m utilizing Visible Studio 2019 to exhibit this instance.

Let’s implement the Cookie Authentication in ASP.NET Core step-by-step:

Open the Visible Studio and click on on Create a brand new Challenge.

Choose ASP.NET Core Empty undertaking and click on on subsequent.

Give a reputation to your Challenge, choose the placement for the undertaking creation, and click on on Subsequent.

Choose the Goal Framework. I’m utilizing .Internet Core 3.1 (LTS) and click on on create.

An identical sort of undertaking as proven within the beneath picture will likely be created.

As we’ve got created an empty undertaking, let’s open the Startup.cs file and add the highlighted code. Within the ConfigureServices technique, I’ve added the AddControllersWithViews service and added the UseEndpoints middleware in Configure technique as proven within the beneath picture.

Add a Controllers folder within the undertaking through which we are going to create all of the controllers.

Let’s add a HomeController by right-clicking on the Controller folder. Go to Add and click on on Controller. Choose the empty controller as proven within the beneath picture.

Proper-click on the undertaking and click on on handle NuGet Packages. Browse Bootstrap (solely required for the UI Model) and click on on Set up.

With a view to serve the static information like js, css, pictures, and many others., we have to UseStaticFiles middleware in Configure technique.

I’ve added to Motion strategies in HomeController i.e., Index and ConfidentialData.

So, on clicking on the House and confidential Information hyperlink within the navigation beneath display screen will likely be proven. 

One other controller i.e., AccountController with a Login web page as proven within the beneath picture.

In ConfigureServices technique of Startup.cs, create an Authentication Middleware Providers with the AddAuthentication and AddCookie technique. Authentication scheme handed to AddAuthentication units to the default authentication scheme for the app. CookieAuthenticationDefaults.AuthenticationScheme gives “Cookies” for the scheme. In AddCookie extension technique, set the LoginPath property of CookieAuthenticationOptions to “/account/login”. CookieAuthenticationOptions class is used to configure the authentication supplier choices.

In Configure technique of Startup.cs, name UseAuthentication and UseAuthorization technique earlier than calling the endpoints.

Now let’s add the Authorize attribute, on ConfidentialData motion technique. Now solely authenticate strategies can entry that ActionMethod.

Let’s click on on Confidential Information hyperlink within the navbar. It can redirect to “Account/Login” web page because the person is just not authenticated but.

In AccountController, the Login motion technique receives the returnurl as a parameter to which the person must be redirected after the profitable authentication. Under is the Login.cshtml code used within the instance.

@mannequin
CookieAuthentication.Fashions.LoginModel

 

@{

   
ViewData[
“Title”] = “Login”;

   
Format =
“~/Views/Shared/_Layout.cshtml”;

}

 

<h2>Login</h2>

 

<hr />

<div class=”row”>

   
<div class=”col-md-4″>

        <kind asp-action=”Login”>

            <div asp-validation-summary=”ModelOnly“ class=”text-danger”></div>

            @if (!string.IsNullOrEmpty(ViewBag.Message))

            {

                <span class=”text-danger”>

                    @ViewBag.Message

                </span>

            }

            @Html.HiddenFor(x => x.ReturnUrl)

            <div class=”form-group”>

                <label asp-for=”UserName“ class=”control-label”></label>

                <enter asp-for=”UserName“ class=”form-control” />

                <span asp-validation-for=”UserName“ class=”text-danger”></span>

            </div>

            <div class=”form-group”>

                <label asp-for=”Password“ class=”control-label”></label>

                <enter asp-for=”Password“ class=”form-control” />

                <span asp-validation-for=”Password“ class=”text-danger”></span>

            </div>

            <div class=”form-group”>

                <div class=”checkbox”>

                    <label>

                        <enter asp-for=”RememberLogin“ /> @Html.DisplayNameFor(mannequin
=> mannequin.RememberLogin)

                    </label>

                </div>

            </div>

            <div class=”form-group”>

                <enter sort=”submit” worth=”Login” class=”btn
btn-default”
/>

            </div>

        </kind>

   
</div>

</div>

LoginModel.cs file:

public class LoginModel

{

        [Required]

        [Display(Name =“Username”)]

        public string UserName { get; set; }

        [Required]

        [DataType(DataType.Password)]

        public string Password { get; set; }

        public bool
RememberLogin {
get; set; }

        public string ReturnUrl { get; set; }

 

}

On clicking on the login button, the Login Publish motion will likely be triggered. In Publish motion, we’re verifying the username and password (On this instance, I’m utilizing the hardcoded person particulars, however in precise you possibly can confirm the person particulars with an ORM like EntityFramework, Dapper, and many others. If entered credentials usually are not legitimate then an Invalid credential message will likely be proven to the person. If credentials are right create a ClaimsIdentity with the required Claims. Name the SignInAsync to signal within the person.

public class AccountController : Controller

{

        //Pattern
Customers Information, it may be fetched with using any ORM

        public Checklist<UserModel> customers = null;

        public AccountController()

        {

            customers = new Checklist<UserModel>();

            customers.Add(new UserModel() { UserId = 1,
Username =
“Anoop”, Password = “123”, Position = “Admin” });

            customers.Add(new UserModel() { UserId = 2,
Username =
“Different”, Password = “123”, Position = “Consumer” });

        }

 

        public IActionResult Login(string ReturnUrl = “/”)

        {

            LoginModel objLoginModel = new LoginModel();

            objLoginModel.ReturnUrl =
ReturnUrl;

            return View(objLoginModel);

        }

        [HttpPost]

        public async
Job<IActionResult> Login(LoginModel objLoginModel)

        {

            if (ModelState.IsValid)

            {

                var person = customers.The place(x =>
x.Username == objLoginModel.UserName && x.Password ==
objLoginModel.Password).FirstOrDefault();

                if (person == null)

                {

                    //Add logic right here to show some message to person

                    ViewBag.Message = “Invalid Credential”;

                    return View(objLoginModel);

                }

                else

                {

                    //A declare is an announcement a couple of topic by an issuer and

                    //characterize attributes of the topic which can be helpful within the
context of authentication and authorization operations.

                    var claims = new Checklist<Declare>() {

                    new
Declare(ClaimTypes.NameIdentifier,Convert.ToString(person.UserId)),

  
                 
new
Declare(ClaimTypes.Title,person.Username),

                    new Declare(ClaimTypes.Position,person.Position),

                    new Declare(“FavoriteDrink”,“Tea”)

                    };

                    //Initialize a brand new occasion of the ClaimsIdentity with the
claims and authentication scheme

                    var id = new ClaimsIdentity(claims,
CookieAuthenticationDefaults.AuthenticationScheme);

                    //Initialize a brand new occasion of the ClaimsPrincipal with
ClaimsIdentity

 
                  
var principal = new ClaimsPrincipal(id);

                    //SignInAsync is a Extension technique for Sign up a principal for
the desired scheme.

                    await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,

                        principal, new AuthenticationProperties() {
IsPersistent = objLoginModel.RememberLogin });

 

                    return
LocalRedirect(objLoginModel.ReturnUrl);

                }

            }

            return View(objLoginModel);

        }

 

        public async
Job<IActionResult> LogOut() {

            //SignOutAsync
is Extension technique for SignOut

            await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //Redirect
to house web page

            return LocalRedirect(“/”);

        }

}

As soon as the person is efficiently logged in to the appliance, a cookie will likely be generated as proven within the beneath picture. This encrypted cookie will likely be despatched to the server in every request and validated on the server with its key.

With a view to present the Claims data on Confidential Information view, code, as proven within the beneath, is used. Within the beneath code, we’re checking that the person should be Authenticated earlier than looping by means of every Claims.

Logout hyperlink is proven to the person who’s already signed in. On Clicking on the Logout hyperlink, we’re calling the SignOutAsync technique which indicators out the person and deletes their cookie.

public async
Job<IActionResult> LogOut() {

            //SignOutAsync
is Extension technique for SignOut

            await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //Redirect
to house web page

            return LocalRedirect(“/”);

}

Closing Preview:

I hope this
article helped you in implementing Cookie Authentication in ASP.

[Download Source code via Google Drive]

You can too get the code by means of the GitHub

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments