Wednesday, October 5, 2022
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 you can implement Cookie Authentication in ASP.NET Core with out utilizing Identification. I’ll attempt to cowl each step in order that learners can simply perceive.

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

Authentication is the method of verifying the identification of the consumer.  On this article, we are going to authenticate the consumer by verifying the consumer’s credentials. I’m utilizing Visible Studio 2019 to display 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 Mission.

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

Give a reputation to your Mission, choose the situation for the venture creation, and click on on Subsequent.

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

The same type of venture as proven within the beneath picture will probably be created.

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

Add a Controllers folder within the venture 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 venture and click on on handle NuGet Packages. Browse Bootstrap (solely required for the UI Model) and click on on Set up.

To be able to serve the static recordsdata like js, css, photos, and so forth., we have to UseStaticFiles middleware in Configure methodology.

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

So, on clicking on the Dwelling and confidential Knowledge hyperlink within the navigation beneath display will probably be proven. 

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

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

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

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

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

In AccountController, the Login motion methodology receives the returnurl as a parameter to which the consumer 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″>

        <type 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>

        </type>

   
</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 probably be triggered. In Publish motion, we’re verifying the username and password (On this instance, I’m utilizing the hardcoded consumer particulars, however in precise you’ll be able to confirm the consumer particulars with an ORM like EntityFramework, Dapper, and so forth. If entered credentials should not legitimate then an Invalid credential message will probably be proven to the consumer. If credentials are appropriate create a ClaimsIdentity with the required Claims. Name the SignInAsync to signal within the consumer.

public class AccountController : Controller

{

        //Pattern
Customers Knowledge, it may be fetched with the usage of any ORM

        public Checklist<UserModel> customers = null;

        public AccountController()

        {

            customers = new Checklist<UserModel>();

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

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

        }

 

        public IActionResult Login(string ReturnUrl = “/”)

        {

            LoginModel objLoginModel = new LoginModel();

            objLoginModel.ReturnUrl =
ReturnUrl;

            return View(objLoginModel);

        }

        [HttpPost]

        public async
Activity<IActionResult> Login(LoginModel objLoginModel)

        {

            if (ModelState.IsValid)

            {

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

                if (consumer == null)

                {

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

                    ViewBag.Message = “Invalid Credential”;

                    return View(objLoginModel);

                }

                else

                {

                    //A declare is an announcement a few topic by an issuer and

                    //signify attributes of the topic which might be helpful within the
context of authentication and authorization operations.

                    var claims = new Checklist<Declare>() {

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

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

                    new Declare(ClaimTypes.Function,consumer.Function),

                    new Declare(“FavoriteDrink”,“Tea”)

                    };

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

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

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

 
                  
var principal = new ClaimsPrincipal(identification);

                    //SignInAsync is a Extension methodology for Sign up a principal for
the required scheme.

                    await
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,

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

 

                    return
LocalRedirect(objLoginModel.ReturnUrl);

                }

            }

            return View(objLoginModel);

        }

 

        public async
Activity<IActionResult> LogOut() {

            //SignOutAsync
is Extension methodology for SignOut

            await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //Redirect
to house web page

            return LocalRedirect(“/”);

        }

}

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

To be able to present the Claims info on Confidential Knowledge view, code, as proven within the beneath, is used. Within the beneath code, we’re checking that the consumer have to be Authenticated earlier than looping via every Claims.

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

public async
Activity<IActionResult> LogOut() {

            //SignOutAsync
is Extension methodology for SignOut

            await
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //Redirect
to house web page

            return LocalRedirect(“/”);

}

Ultimate Preview:

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

[Download Source code via Google Drive]

It’s also possible to get the code via the GitHub

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments