Use Cookie middleware and cookie middleware in ASP. NET Core
Use Cookie middleware in http: // ASP. NET Core
ASP. NET Core provides Cookie middleware to serialize a User's subject to an encrypted Cookie and verify the Cookie in subsequent requests, reproduce the User and assign it to the User attribute of the HttpContext object. If you want to provide your own login method and user data, you can use Cookie middleware to implement independent functions.
Add and configure
The first step is to add the Cookie middleware to your application. First, use nuget to add the Microsoft. AspNetCore. Authentication. Cookies package. Then add the following lines of code to the Configure method of the Startup. cs file, and before app. UseMvc.
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", LoginPath = new PathString("/Account/Unauthorized/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
Several options are configured in the code snippet above;
- Authentication Scheme: This is the value of a known middleware. This option takes effect if you want to restrict the permission to one instance for middleware with multiple instances.
- Logon path: this is when the user tries to access the resource but has not been authenticated, the program will redirect the request to this relative path.
- Forbidden access path: when a user attempts to access a resource but does not pass any authorization policy of the resource, the request will be redirected to this relative path.
- Automatic authentication: this flag indicates that the middleware should verify and recreate the serialized entity created by the middleware on each request.
- Automatic challenge: this flag indicates that when the middleware authentication fails, the browser should be redirected to the logon path or the access path is forbidden.
Other options include setting the issuer of the Declaration created by the middleware, the cookie name stored by the middleware, the Cookie domain, and various security attributes on the cookie. By default, Cookie-Oriented Middleware uses appropriate security options to set HTTPONLY to prevent the cookie from being operated by JavaScript on the client. When the request method is HTTPS, the HTTPS operation for Cookie generation is limited.
Create Cookie
Create a Cookie to save your own information. You must initialize a ClaimsPrincipal (type) to serialize and save the user information you want to save to the Cookie. Each method call has a suitable ClaimsPrincipal object in your Controller.
Copy codeThe Code is as follows:
Await HttpContext. Authentication. SignInAsync ("MyCookieMiddlewareInstance", principal );
The above Code creates an encrypted Cookie and adds it to the current request response. AuthenticationScheme explicitly specifies that during configuration
Exit
Log out of the current user and delete the cookie information. You can call the following method in the controller.
Copy codeThe Code is as follows:
Await HttpContext. Authentication. SignOutAsync ("MyCookieMiddlewareInstance ");
Response to backend changes
Warning
Once a cookie is created, it will become the source of a single authentication. Even if the background system is unavailable, middleware will not know, and it will always log on until the cookie becomes invalid.
Cookie authentication middleware provides a series of events in its option class. Among them, ValidateAsync () events can be used to interrupt and override the verification method of cookie authentication.
Considering that the backend user's database may have the 'last modification time' column, you can abolish the current Cookie after the database is modified, first, when this Cookie is created, a last modified declaration is added and the current value is included. When the data in the database changes, this value is also updated.
To implement a ValidateAsync () event rewrite, you must write a method with the following signature.
Task ValidateAsync(CookieValidatePrincipalContext context);
Http: // ASP. NET Core authentication implements this authentication in SecurityStampValidator. The following is a similar example:
public static class LastChangedValidator { public static async Task ValidateAsync(CookieValidatePrincipalContext context) { // Pull database from registered DI services. var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>(); var userPrincipal = context.Principal; // Look for the last changed claim. string lastChanged; lastChanged = (from c in userPrincipal.Claims where c.Type == "LastUpdated" select c.Value).FirstOrDefault(); if (string.IsNullOrEmpty(lastChanged) || !userRepository.ValidateLastChanged(userPrincipal, lastChanged)) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); } } }
These must be registered during Cookie middleware configuration.
app.UseCookieAuthentication(options => { options.Events = new CookieAuthenticationEvents { // Set other options OnValidatePrincipal = LastChangedValidator.ValidateAsync }; });
If you want to update the user subject non-destructive, for example, if the name is updated, you can call context. ReplacePrincipal () and set context. ShouldRenew to true in a way that does not affect security.
Cookie control options
CookieAuthenticationOptions comes with a variety of configuration options that allow you to properly adjust the created cookies.
- ClaimsIssuer-used to create attributes on any middleware. (Do not understand)
- CookieDomain-if the cookie domain is set to **. http: // contoso.com **, such domain names as contoso.com, http: // www. contoso.com, staging.contoso.com, and so on will also be allowed.
- CookieHttpOnly-this flag indicates that the cookie will only be accessed by the server. The default value is true. modifying this attribute will enable your application to cause Cookie Theft and cause cross-site scripting bugs.
- CookiePath-this can be used to isolate applications running on the same host. If you have an application running on/app1 and want to restrict the cookie from being sent only to yourself, you should set the CookiePath attribute to/app1; the Cookie will understand that it only applies to the path/app1 or other requests.
- ExpireTimeSpan-after this TimeSpan period, the Cookie will expire.
- SlidingExpiration-this flag indicates that if half of the expiration time is reached, the Cookie will be reset. The new expiration time is later than the current time plus ExpireTimespan. When SignInAsync is called, you can use ** AuthenticationProperties ** to set the absolute expiration time. By limiting the time for verification of cookie validity, the absolute expiration can improve the security of the application.
Persistent Cookie and absolute expiration time
You may want to make the cookie expire through a browser session. You may also want to end the cookie through the absolute expiration time and Authentication, so you can use the AuthenticationProperties parameter class in the HttpContext. Authentication. SignInAsync method when logging on to the Authentication and creating the Cookie. The AuthenticationProperties class is in the Microsoft. AspNetCore. Http. Authentication namespace.
For example
await HttpContext.Authentication.SignInAsync( "MyCookieMiddlewareInstance", principal, new AuthenticationProperties { IsPersistent = true });
This code snippet creates an authentication and corresponding Cookie to enable the instant browser to disable the Cookie and retain it. Any expiration time setting in the cookie property will be saved. If the Cookie expires when the browser is closed, the Cookie will not be cleared when the browser is restarted.
await HttpContext.Authentication.SignInAsync( "MyCookieMiddlewareInstance", principal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20) });
This Code creates an identity authentication and cookie for 20 minutes. Any dynamic options configured in Cookie options will be ignored. ExpiresUtc and IsPersistent attributes are independent of each other.
In fact, it is useless if there are so many bb instances above! Let's try a demo.
// 1. Add app. UseCookieAuthentication (new CookieAuthenticationOptions {AuthenticationScheme = "UserAuth" to the Configure method of Startup. cs, // The Name Of The Cookie authentication scheme, which will be used when writing cookies. AutomaticAuthenticate = true, // whether verification is automatically enabled. If verification is not enabled, the server does not parse the Cookie information even if the client transmits the Cookie information. In addition to explicitly configuring the [Authorize (ActiveAuthenticationSchemes = "solution name above")] attribute, this function is generally used when you need to enable multiple verification schemes in the same application. For example, Area. loginPath = "/User/Index" // logon page}); // 2. create UserController // 3. create a test logon method (here I use the get method to facilitate the test and facilitate parameter request passing) public IActionResult Login (int userId, string userName) {WriteUser (userId, userName); return Content ("Write");} private async void WriteUser (int userId, string userName) {var identity = new ClaimsIdentity ("Forms "); // specify the identity authentication type. addClaim (new Claim (ClaimTypes. sid, userId. toString (); // user ID identity. addClaim (new Claim (ClaimTypes. name, userName); // user Name var principal = new ClaimsPrincipal (identity); await HttpContext. authentication. signInAsync ("UserAuth", principal, new AuthenticationProperties {IsPersistent = true, ExpiresUtc = DateTime. utcNow. addMinutes (20)}); // expiration time: 20 minutes} // 4. create a public async Task <ActionResult> Logout () {await HttpContext. authentication. signOutAsync ("UserAuth"); // Startup. return RedirectToAction ("User", "Index");} // 5. create a method to obtain cookie User information to call private int GetUserId () {// var userName = User. identity. name; // obtain the User Name stored during logon var userId = User. findFirst (ClaimTypes. sid ). value; // obtain the Id if (string. isNullOrEmpty (userId) {return 0;} else {return int. parse (userId) ;}}// or write a test Actionpublic JsonResult CheckLogin () {var userName = User. identity. name; // obtain the User Name stored during logon var userId = User. findFirst (ClaimTypes. sid ). value; // obtain the Id return Json ({UserId: userId, UserName: userName}) stored during logon;} // 6. the above is the encryption method. If you write it directly, it seems that it is also possible to use HttpContext. response. cookies. append ("Key", "Value ");
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.