Use the Cookie authentication method in ASP. NET Learning CORE,

Source: Internet
Author: User

Use the Cookie authentication method in ASP. NET Learning CORE,

You must have used FormsAuthentication for identity authentication when using ASP. NET. The core of FormsAuthentication is Cookie, and ASP. NET stores user names in cookies.

Now we are in the ASP. net core era, but ASP. net core does not have FormsAuthentication. How can we implement identity authentication? The answer is that ASP. net core has built the Cookie identity authentication function for us, and it is very convenient to use. Note that this article describes the Cookie Authentication Method Based on ASP. net core 2.0.

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 the Cookie authentication middleware in the project's OWIN framework file Startup. cs.

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

Public void ConfigureServices (IServiceCollection services) {services. AddMvc (); // register the Cookie authentication service services. AddAuthentication (cookieauthenticationults ults. AuthenticationScheme). AddCookie ();}

Use app. UseAuthentication in Configure method of Startup to enable Cookie authentication middleware (note that the call sequence 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 () {app. usemediaexceptionpage (); app. useBrowserLink ();} else {app. useExceptionHandler ("/Home/Error");} app. useStaticFiles (); // pay attention to the app. the UseAuthentication method must be placed in the following app. before UseMvc method, if not, HttpContext is called. after SignInAsync logs on to the user, use // HttpContext. the User still shows that the User has not logged on and HttpContext. user. claims cannot read any information of the login user. // This indicates Asp. in the Net OWIN framework, the call sequence of MiddleWare has a great impact on system functions. The call sequence of each MiddleWare cannot be reversed. useAuthentication (); app. useMvc (routes => {routes. mapRoute (name: "default", template: "{controller = Home}/{action = Index}/{id ?} ");});}

2. Login User

The methods for logging on to users using Cookie authentication in ASP. net core are not the same as those in traditional FormsAuthentication. The steps are as follows:

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

In this example, we create an Acion method Login in the default HomeController in the project to implement the user Login code. Of course, here we implement the simplest Cookie login. In the code below, we can also set whether the Cookie is persistent, how long the Cookie expires, and what is the name of the Cookie that stores the login user information, we will not introduce it 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> /// this Action logs on to the user Wangdacui to Asp. net Core /// </summary> public IActionResult Login () {// The claims variable is an array of the Claim type, and Claim is a key-value pair of the string type, therefore, the claims array can store any user-related information. // note that the information is encrypted and stored in the client browser cookie, so it is better not to store too much sensitive information. Here we only store the user name to the claims array, // indicates who is currently logged on. var claims = new [] {new Claim ("UserName", "Wangdacui")}; var claimsIdentity = new ClaimsIdentity (claims, cookieauthenticationults ults. authenticationSch Eme); ClaimsPrincipal user = new ClaimsPrincipal (claimsIdentity); // Login user, equivalent to ASP. formsAuthentication. setAuthCookieHttpContext. signInAsync (cookieauthenticationults ults. authenticationScheme, user ). wait (); // you can use HttpContext. the reload of the SignInAsync method defines persistent cookies to store user authentication information. For example, the following code defines that cookies will be stored on the client's computer hard disk within 60 minutes after a user logs on, // even if the browser is closed, the user can log on to the site again within 60 minutes, unless the Logout method is called to log out. /* HttpContext. signInAsync (cookieauthenticationults ults. authenticationScheme, user, new AuthenticationProperties () {IsPersistent = true, ExpiresUtc = DateTimeOffset. now. addMinutes (60 )}). wait (); */return View ();}

3. Read login user information

So how can I read the information of the logged-on user (such as the user name) after the user logs on? The Index method of HomeController demonstrates how to determine whether the current user has logged on and read the user name. The code for the Index method is as follows:

/// <Summary> /// this Action determines whether the user has logged on. If the user has logged on, read the username of the logged on user. /// </summary> public IActionResult Index () {// If HttpContext. user. identity. isAuthenticated is true, // or HttpContext. user. claims. if the value of Count () is greater than 0, the user has logged on to if (HttpContext. user. identity. isAuthenticated) {// use HttpContext. user. claims can read all the // claims key-value pairs stored in the cookie in the Action Login, for example, the UserName value Wangdacui defined just now reads var userName = HttpContext. user. claims. first (). value;} return View ();}

4. log out of the user

How can I log out after logging on to the user? The Logout method of HomeController demonstrates how to log out of a logon user. The Code is as follows:

/// <Summary> /// the Action is taken from Asp.. Net Core: the logged-out user /// </summary> public IActionResult Logout () {// the logged-out user, which is equivalent to ASP. formsAuthentication. signOut HttpContext. signOutAsync (). wait (); return View ();}

As mentioned above, you can also set the Cookie name and persistence storage in the Cookie authentication of ASP. net core.

The above is all the content of this small Editor. Thank you for your support for the help house.

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.