Dot Net Stuff

Custom Cookie Authentication In ASP.NET Core


This article covers Cookie Authentication in ASP.net Core 1.X. While much is the same in resulting forms, there are a few little changes that could trip you up. Investigate our article on Cookie Authentication in ASP.net Core 2.0.

ASP.net core accompanies two approaches to do authentication out of the crate. The first is utilizing ASP.net cores "character" benefit that wraps a MSSQL set of tables and enables you to get each bit of usefulness out of the crate, however requires you to have an extremely unbending structure and do things the "Microsoft" way. It additionally expects you to utilize a database connector that has been pre-fabricated (Typically this implies utilizing Microsoft SQL). In the event that you are utilizing something like a NoSQL database store to your clients, or you verify your clients utilizing an option that is other than a username secret key mix, at that point utilizing the full character administration can be somewhat of an agony.

The option is to utilize ASP.net Core's "Cookie Authentication" which enables you to utilize cookie based cases for a client, yet verify the clients yourself utilizing your own information store, however that may work. That is the thing that this article will concentrate on. Setup

In the event that you are making a spic and span venture utilizing Visual Studio for this instructional exercise, guarantee that while making your task you select the "authentication type" to be none. We basically need to begin with a fresh start.

In your nuget package manager window, install the following package :

Install-Package Microsoft.AspNetCore.Authentication.Cookies

In your startup.cs file, find your configure method. You should add the following code to your pipeline but you must ensure this is before your call to “AddMvc”. This is extremely important. Your pipeline runs in the order you have added it so you need to obviously have authorization run before MVC kicks in.

 
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
	AuthenticationScheme = "CookieAuthentication",
	LoginPath = new PathString("/Account/Login"),
	AccessDeniedPath = new PathString("/Account/Forbidden/"),
	AutomaticAuthenticate = true,
	AutomaticChallenge = true
});

A tiny bit about the alternatives we have set here.

AuthenticationScheme is quite recently the name we have given this example of authentication. You can really have numerous authentication middleware in your application. The name isn't excessively imperative and can be anything in the event that you are just having the single login.

  • LoginPath is the way to your login page
  • AccessDeniedPath is the way to a "denied" page
  • AutomaticAuthenticate implies that the middleware runs naturally on each demand and tries to verify the client
  • AutomaticChallenge implies that a client ought to naturally be steered to the LoginPage if the client isn't approved.

Enrolling A User

Utilizing Cookie Authentication as a basic middleware and not utilizing the full character benefit implies you have to compose enrolling clients and making them in your information store yourself. There is nothing in the middleware to enable you to out there.

Signing In A User

For signing in, we will make a straightforward post model to acknowledge our username and secret word blend.

 
public class LoginModel
{
	public string Username { get; set; }
	public string Password { get; set; }
}

I’ve created a controller called “AccountController”. Inside I’ve created a GET and POST endpoint for our model. The GET endpoint returns a view that has a simple form for logging in, the POST endpoint is where we do our work.

 
public class AccountController : Controller
{
	[HttpGet]
	public IActionResult Login()
	{
		return View();
	}
 
	[HttpPost]
	public async Task<IActionResult> Login(LoginModel loginModel)
	{
		if(LoginUser(loginModel.Username, loginModel.Password))
		{
			var claims = new List<Claim>
			{
				new Claim(ClaimTypes.Name, loginModel.Username)
			};
 
			var userIdentity = new ClaimsIdentity(claims, "login");
 
			ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
			await HttpContext.Authentication.SignInAsync("CookieAuthentication", principal);
 
			//Just redirect to our index after logging in. 
			return Redirect("/");
		}
		return View();
	}

 
	private bool LoginUser(string username, string password)
	{
		//As an example. This method would go to our data store and validate that the combination is correct. 
		//For now just return true. 
		return true;
	}
}

How about we stroll through that code a bit.

To start with we approve the client. In our illustration we simply approve each client yet clearly, in actuality, this would leave to our information store and approve the Username/Password combination.

Next we make a Claims list. These are things we think about the client that we wish to store on the cookie. In this case I've quite recently put away the Username as the "Name" guarantee. This one is somewhat critical as we see later as there is an alternate way to get this name, yet you can really store any key/esteem mix inside the cases in the event that you would prefer not to need to backpedal to the database each opportunity to get information on the signed in client.

We at that point manufacture a personality, a chief, and afterward set the cookie utilizing the SignInAsync technique. There is a touch of cruft going ahead here regarding building the personality and chief, yet the critical part is building cases and calling signin.

Approving Controllers

Next we clearly need to figure out how to "lockdown" certain ranges of our site to constrain a client to need to login. We can do this basically by including an "Approve" ascribe to any controller.

 
[Authorize]
public class HomeController : Controller
{
	......

And that’s all there is to it! Any user that navigates to this controller will be redirected to your “Logon” url.

Logging Our A User

Logging out a user is very simple.

 
[HttpGet]
public async Task<IActionResult> Logout()
{
	await HttpContext.Authentication.SignOutAsync("CookieAuthentication");
	return Redirect("/Account/Login");
}

That’s really all there is too it! Remember the Authentication Scheme you use here must match the one you set in the middleware setup.

Survey The Logged In User

Clearly eventually we will need to see the signed in client, either to get further insights about the client from the database or set onscreen components in a view. Here we have some illustration code on how we can get both the username we set before, and some other claim we may have set.

 
public IActionResult Index()
{
	var loggedInUser = HttpContext.User;
	var loggedInUserName = loggedInUser.Identity.Name; // This is our username we set earlier in the claims. 
	var loggedInUserName2 = loggedInUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; //Another way to get the name or any other claim we set. 
	return View();
}

The Name on the Identity object is just a fancy way of getting the “Name” claim that we set earlier, but for any other claim you can work with the claims list and fetch our data. Remember this will only be set after logging in so null checks should be done along the way.

Keen to hear from you...!

If you have any questions related to what's mentioned in the article or need help with any issue, ask it, I would love to here from you. Please MakeUseOf Contact and i will be more than happy to help.

About the author

Anil Sharma is Chief Editor of dotnet-stuff.com. He's a software professional and loves to work with Microsoft .Net. He's usually writes articles about .Net related technologies and here to shares his experiences, personal notes, Tutorials, Examples, Problems & Solutions, Code Snippets, Reference Manual and Resources with C#, Asp.Net, Linq , Ajax, MVC, Entity Framework, WCF, SQL Server, jQuery, Visual Studio and much more...!!!

blog comments powered by Disqus