ASP. NET Learning Cookie Authentication Method in CORE

  • 2021-10-16 01:29:37
  • OfStack

When you use ASP. NET, you have used FormsAuthentication as the identity authentication of login users. The core of FormsAuthentication is Cookie, and ASP. NET will store the user name in Cookie.

Now it's the era of ASP. NET CORE, but there is no FormsAuthentication in ASP. NET CORE, so how to do identity authentication? The answer is that ASP. NET CORE has built-in Cookie authentication function for us, and it is very convenient to use. Note that this article is based on ASP. NET CORE version 2.0 to explain Cookie authentication mode.

1. Enable Cookie authentication from the ASP. NET CORE OWIN framework

To use Cookie authentication in ASP. NET CORE, the first step is to enable Cookie authentication middleware in the OWIN framework file Startup. cs in the project.

First, we register the Cookie authentication service with services. AddAuthentication in the ConfigureServices method in Startup, as shown in the following code:


public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  // Registration Cookie Certification services 
  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}

Then use app. UseAuthentication in the Configure method in Startup to enable the Cookie authentication middleware (note that app. UseAuthentication and app. UseMvc cannot be called in reverse order), as shown in the following code:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
  }
  else
  {
    app.UseExceptionHandler("/Home/Error");
  }
  app.UseStaticFiles();
  // Attention app.UseAuthentication Method 1 It must be placed below app.UseMvc Method before, or after, call HttpContext.SignInAsync After user login, use the 
  //HttpContext.User It still shows that the user is not logged in, and HttpContext.User.Claims Unable to read any information about the logged-in user. 
  // This shows that Asp.Net OWIN In the framework MiddleWare The call order of will have a great impact on the system function, and each MiddleWare Call order of 1 You can't reverse it 
  app.UseAuthentication();
  app.UseMvc(routes =>
  {
    routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
  });      
}

2. Log in to the user

The method of using Cookie to authenticate login users in ASP. NET CORE is different from that of traditional FormsAuthentication, and the general steps are as follows:

Create an array of type Claim and store all the information of the logged-in user (such as user name) in a string key-value pair of type Claim
Pass the array of type Claim created above into ClaimsIdentity to construct an ClaimsIdentity object
Pass the ClaimsIdentity object created above into ClaimsPrincipal to construct an ClaimsPrincipal object
Call the HttpContext. SignInAsync method and pass in the ClaimsPrincipal object created above to complete the user login
Therefore, we can see that the whole Cookie authentication login process of ASP.NET CORE is much more complicated than the previous FormsAuthentication of ASP. NET. After all, the previous FormsAuthentication. SetAuthCookie method was completed.

In the example of this article, we created an Acion method Login in the default HomeController in the project to realize the user login code. Of course, what we realize here is the simplest Cookie login. In the following code, we can actually set whether Cookie is persistent, how long Cookie expires, what is the name of Cookie storing login user information, etc. We won't introduce too much. You can read the two official documents recommended at the end of this article to learn more.

The code for the Login method is as follows:


/// <summary>
///  The Action Login user Wangdacui To Asp.Net Core
/// </summary>
public IActionResult Login() {
	// The following variables claims Yes Claim An array of type, Claim Yes string A key-value pair of type, so claims Arrays can store any number of user-related information, 
	// However, it should be noted that this information is encrypted and stored in the client browser cookie So it's best not to store too much particularly sensitive information, here we only store the user name to 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 ASP.NET In FormsAuthentication.SetAuthCookie
	HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user).Wait();
	// You can use the HttpContext.SignInAsync Method to define persistence cookie Store user authentication information, for example, the following code defines the user after logging in 60 Within minutes cookie Will remain on the hard disk of the client computer, 
	// Even if the user closes the browser, 60 If you visit the site again within minutes, you will still be logged in unless you call Logout Method logs out of the login. 
	/*
  HttpContext.SignInAsync(
  CookieAuthenticationDefaults.AuthenticationScheme,
  user, new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = DateTimeOffset.Now.AddMinutes(60) }).Wait();
  */
	return View();
}

3. Read login user information

Then how can the information (such as user name) of the logged-in user be read out after the user logs in? In the Index method of HomeController, we demonstrated how to determine whether the current user has logged in and read out the user name of the logged-in user. The code of the Index method is as follows:


/// <summary>
///  The Action Judging whether the user has logged in, if so, reading the user name of the logged-in user 
/// </summary>
public IActionResult Index()
{
  // If HttpContext.User.Identity.IsAuthenticated For true , 
  // Or HttpContext.User.Claims.Count() Greater than 0 Indicates that the user has logged in 
  if (HttpContext.User.Identity.IsAuthenticated)
  {
    // Through here  HttpContext.User.Claims  Can put us in Login This Action Store in the cookie All in 
    //claims The key-value pairs are read out, such as the one we just defined UserName Value of Wangdacui It's read right here 
    var userName = HttpContext.User.Claims.First().Value;
  }
  return View();
}

4. Log off users

So how to log off after logging in to the user? We demonstrated how to log off a logged-in user in HomeController's Logout method, with the following code:


/// <summary>
///  The Action From Asp.Net Core User logged off in 
/// </summary>
public IActionResult Logout()
{
  // User who logs off, equivalent to ASP.NET In FormsAuthentication.SignOut 
  HttpContext.SignOutAsync().Wait();
  return View();
}

As mentioned earlier, in fact, the name of Cookie, whether it is persisted or not can also be set in Cookie authentication of ASP. NET CORE.

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


Related articles: