Detailed introduction to How to use cookie Middleware in ASP.

Source: Internet
Author: User
This article mainly introduces the use of cookie middleware in the ASP. NET Core, has certain reference value, the interested small partners may refer to

Using cookie Middleware in HTTP./ASP.

ASP. NET Core provides cookie middleware to serialize user themes into an encrypted cookie and later request that the cookie be re-reproduced and assigned to the user attribute of the HttpContext object. If you want to provide your own login and user data, you can use cookie middleware to achieve independent functionality.

Add and configure

The first step is to add the cookie middleware to your application. First add the Microsoft.AspNetCore.Authentication.Cookies package using NuGet. 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});

The code snippet above configures a few options;

    1. Authentication scheme: This is the value of a known middleware, when there are multiple instances of the middleware if you want to restrict authorization to an instance, this option will work.

    2. Logon path: This is when a user attempts to access a resource but is not authenticated, the program redirects the request to the relative path.

    3. Forbidden Path: When a user tries to access a resource, but does not pass any authorization policy for that resource, the request is redirected to this relative path.

    4. Automatic authentication: This flag indicates that the middleware should validate on each request and rebuild the serialization principal that he created.

    5. Auto Challenge: This flag indicates that the browser should be redirected to a login path or a forbidden path when the middleware authentication fails.

Other options include setting the publisher of the claims created by the middleware, the cookie name stored by the middleware, the domain of the cookie, and various security attributes on the cookie. By default, the cookie middleware will use the appropriate security options to set HttpOnly to avoid cookies being manipulated by JavaScript on the client. Restricts the HTTPS operation of the cookie when the request mode is HTTPS.

Create a cookie

To 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 into the cookie. Each method call will have a suitable Claimsprincipal object in your controller.

Copy the Code code as follows:

Await HttpContext.Authentication.SignInAsync ("Mycookiemiddlewareinstance", principal);

The above code will create an encrypted cookie and add it to the current request response. Authenticationscheme expressly stated during the configuration

Exit

Exit the current user's login, delete the login cookie information, you can call the following method in the controller.

Copy the Code code as follows:

Await HttpContext.Authentication.SignOutAsync ("mycookiemiddlewareinstance");

Response back-end changes

Warning

Once a cookie is created, it becomes a source of identity authentication, and even if the backend system is unavailable, the middleware is unaware and remains logged in until the cookie expires.

The cookie authentication middleware provides a series of events in his options class where the Validateasync () event can be used to interrupt and rewrite authentication methods for cookie authentication.

Considering that there may be a ' last modified ' column in the database for the background user, in order to revoke the current cookie after the database has been modified, first add a last modified declaration and include the current value when the cookie is created, and the value is updated when the data in the database changes.

Implement a Validateasync () event rewrite you must write a method that has the following signature.

Task Validateasync (cookievalidateprincipalcontext context);

The ASP. NET Core certification implements this validation 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 the C in Userprincipal.claims       where c.type = = "LastUpdated"       select C.value). FirstOrDefault ();   if (string. IsNullOrEmpty (lastchanged) | |    ! Userrepository.validatelastchanged (Userprincipal, lastchanged))   {    context. Rejectprincipal ();    Await the context. HttpContext.Authentication.SignOutAsync ("Mycookiemiddlewareinstance");   }  } }

These are to be registered when the cookie middleware is configured

App. Usecookieauthentication (options =  options. Events = new Cookieauthenticationevents  {   //Set other options   Onvalidateprincipal = Lastchangedvalidator.validateasync  }; });

If you want to update the user principal non-destructively, for example, name is updated, you can invoke the context in a way that does not affect security. Replaceprincipal () and set the context. Shouldrenew is true.

Control cookie Options

Cookieauthenticationoptions is equipped with a variety of configuration options that you can fine tune to create the cookie.

    1. Claimsissuer-is used to create attributes on any middleware. (Can not understand)

    2. Cookiedomain-If cookie domain is set to * *. http://contoso.com * * so contoso.com, http://www. Contoso.com,staging.contoso.com and so on will be allowed.

    3. Cookiehttponly-This flag indicates that the cookie will only be accessed by the server. The default value is true, modifying this property will open your app to cause Cookie theft, causing cross-site scripting bugs.

    4. Cookiepath-This can be used to isolate applications running under the same host. If you have an app running on/app1 and want to limit the cookie limit to just being sent to yourself, then you should set the Cookiepath property to/app1; The cookie will understand that it only applies to Tao/app1 or his request below.

    5. Expiretimespan-The Cookie expires after this TimeSpan period.

    6. SlidingExpiration-This flag marks the cookie will be reset if it is accessed half of the expiration time. The new expiration time will be moved back to the current time after adding Expiretimespan. When calling Signinasync, you can set an absolute expiration time by * * authenticationproperties * * *. By limiting the time that validation cookies are valid, an absolute expiry can improve the security of your application.

Persistent cookie and absolute expiration time

You may want to expire the cookie through a browser session. You may also want to end cookies with an absolute expiration date and a certification. Then you can use the Authenticationproperties parameter class in the HttpContext.Authentication.SignInAsync method when signing in for authentication and creating cookies. 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 will be implemented to create an authentication and corresponding cookie to enable the Instant browser close cookie to be retained. Any setting of the expiration time in the cookie attribute will be saved. If the cookie expires when the browser is closed, then the cookie will not be cleaned when the browser is restarted.

Await HttpContext.Authentication.SignInAsync (  "Mycookiemiddlewareinstance",  Principal,  New Authenticationproperties  {   EXPIRESUTC = DateTime.UtcNow.AddMinutes  });

This code will create an identity certificate and the corresponding cookie and will last for 20 minutes. Any dynamic options configured in the cookie options will be ignored. The two properties of EXPIRESUTC and Ispersistent are independent of each other.

In fact, the above BB so much, are useless! Why don't you get a demo?

1. Add App.usecookieauthentication to the Configure method of Startup.cs (new cookieauthenticationoptions{authenticationscheme = " Userauth ",//cookie authentication scheme name, which is used when writing a cookie. Automaticauthenticate = True,//whether authentication is enabled automatically, and if not enabled, the server does not actively parse the cookie if it is transmitted by the client. This is only resolved where the [authorize (Activeauthenticationschemes = "scheme name") property is explicitly configured, which is typically used when multiple validation scenarios need to be enabled in the same application. such as sub-area. Loginpath = "/user/index"//Login page});//2. New usercontroller//3. Create a test login method (here for the convenience of testing is I use the Get method, convenient for parameter request) 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"); Specifies the authentication type identity.  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 method to sign out public async task<actionresult> Logout () {await HttpContext.Authentication.SignOutAsync ("Userauth" ); The authentication scheme name configured in Startup.cs return redirecttoaction ("User", "Index");} 5. Create a method to get cookie user information convenient to call private int GetUserId () {//var userName = User.Identity.Name;//Get the user name stored at login var userId = User.fin DFirst (CLAIMTYPES.SID). Value; Gets the ID that is stored at login if (string. IsNullOrEmpty (userId)) {return 0;} else {return int. Parse (USERID); }}//or write a test actionpublic jsonresult checklogin () {var userName = User.Identity.Name;//Get the user name stored at login var userId = User.find First (CLAIMTYPES.SID). Value; Gets the ID stored at login return Json ({userid:userid,username:username}); 6. The above is the way of encryption if the direct write seems to be able to HttpContext.Response.Cookies.Append ("Key", "Value");
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.