Using cookie authentication in learning core


When you use, you must have used formsauthentication as the identity authentication of the login user. The core of formsauthentication is cookie. will store the user name in the cookie.

Now it is the age of core, but there is no formsauthentication in core, so how to do identity authentication? The answer is that core has built-in cookie identity authentication function for us, and it is very convenient to use. Note that this paper is based on core version 2.0 to elaborate cookie authentication.

1. Enable cookie identity authentication from core win framework

To use cookie authentication in core, the first step is to enable cookie authentication Middleware in the owin framework file startup.cs in the project.

First, we use services.addauthentication in the configureservices method in startup to register the cookie authentication service, as shown in the following code:

public void ConfigureServices(IServiceCollection services)
  //Register cookie authentication service

Then use app.useauthentication in the configure method of startup to enable cookie authentication middleware (note that the calling order of app.useauthentication and app.usemvc cannot be reversed), as shown in the following code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  if (env.IsDevelopment())
  //Note that the app.useauthentication method must be placed in front of the app.usemvc method below. Otherwise, it is necessary to call httpcontext.signinasync to log in the user
  //Httpcontext.user still shows that the user is not logged in, and cannot read any information of the logged in user.
  //This shows that the call sequence of Middleware in ASP. Net owin framework will have a great impact on the system functions, and the call sequence of each middleware must not be reversed
  app.UseMvc(routes =>
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");

2. Login user

In core, cookie authentication is not the same as traditional formsauthentication. The steps are as follows:

Create an array of claim type, and store all information (such as user name) of the login user in the string key value pair of claim type
Pass the array of claim type created above into claimsidentity to construct a claimsidentity object
Pass the claimsid object created above into claimspricipal to construct a claimspricipal object
Call the httpcontext.signinasync method, pass in the claimspricipal object created above, and complete the user login
So we can see that the cookie authentication login process of the whole core is much more complicated than that of the previous formsauthentication. After all, the previous formsauthentication.setauthcookie method is done.

In the example of this article, we create an action method login in the default homecontroller in the project to implement the code of user login. Of course, we realize the simplest cookie login here. In the following code, we can also set whether the cookie is persistent, how long the cookie expires, and what is the name of the cookie storing the login user information. We won’t introduce it too much. You can read the two official documents recommended in the last part of this article to learn more.

The code of the login method is as follows:

/// <summary>
///The action log in user wangdacui to ASP. Net core
/// </summary>
public IActionResult Login() {
	//The following variable claims is an array of claim type, and claim is a key value pair of string type. Therefore, any user related information can be stored in the claims array,
	//However, it should be noted that these information are encrypted and stored in the cookie of the client browser, so it's better not to store too many particularly sensitive information. Here we only store the user name to the claims array,
	//Indicates who is currently logged in
	var claims = new[] {
		new Claim("UserName", "Wangdacui")
	var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
	ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity);
	//Login user, equivalent to formsauthentication.setauthcookie in
	HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user).Wait();
	//You can use the overload of httpcontext.signinasync method to define persistent cookies to store user authentication information. For example, the following code defines that cookies will remain on the hard disk of the client computer within 60 minutes after the user logs in,
	//Even if the user closes the browser, it is still in the login state to visit the site again within 60 minutes, unless the logout method is called to log out.
  user, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.Now.AddMinutes(60) }).Wait();
	return View();

3. Read login user information

How to read the information (such as user name) of the logged in user after the user logs in? In the index method of homecontroller, we demonstrate how to judge whether the current user has logged in and read out the user name of the logged in user. The code of index method is as follows:

/// <summary>
///This action determines whether the user has logged in. If so, read the user name of the logged in user
/// </summary>
public IActionResult Index()
  //If httpcontext.user.identity.isauthenticated is true,
  //Or httpcontext. User. Claims. Count() is greater than 0, indicating that the user has logged in
  if (HttpContext.User.Identity.IsAuthenticated)
    //Here, through, we can store all of the cookies in the login action
    //Claim key value pairs are read out. For example, the value wangdacui of the username we just defined is read out here
    var userName = HttpContext.User.Claims.First().Value;
  return View();

4. Log off user

So how to log out after logging in? In the logout method of homecontroller, we demonstrate how to log out the logged in user. The code is as follows:

/// <summary>
///This action logs off the logged in user from ASP. Net core
/// </summary>
public IActionResult Logout()
  //Log off the logged in user, equivalent to formsauthentication.signout in 
  return View();

As mentioned above, in fact, in the cookie authentication of core, you can also set the cookie name, whether to persist the storage, etc.

The above is the whole content of this compilation. Thank you for your support for developepaer.