ASP. NET Core series "four" based on claim login authorization

Source: Internet
Author: User
Tags httpcontext

Original: ASP. NET Core series "four" based on claim login authorization

Introduced

About what is claim?

Take a look at other great gods articles:

Http://www.cnblogs.com/jesse2013/p/aspnet-identity-claims-based-authentication-and-owin.html

Http://www.cnblogs.com/savorboard/p/aspnetcore-identity.html

Note: I am still rookie beginner stage, if there is wrong place, hope you big Bird point!

Scene

User login is a very common scenario. NET Core login is a bit different from the past, can be said to be in the direction of good development, become more easy to expand, more convenient.

In the previous chapter, there has been a brief introduction, then this chapter, let us take a closer look.

Configuration

1. First you need nuget to install a package:Microsoft.AspNetCore.Authentication.Cookies

Open the Startup.cs file in the project and find the Configureservices method, which we usually do with dependency injection configuration in this method.

 Public voidconfigureservices (iservicecollection services) {//Add Cookie Middleware configurationServices. Addauthentication (options ={options. Defaultauthenticatescheme="Mycookieauthenticationscheme"; Options. Defaultchallengescheme="Mycookieauthenticationscheme"; Options. Defaultsigninscheme="Mycookieauthenticationscheme"; })            . Addcookie ("Mycookieauthenticationscheme", options =            {                //options. Accessdeniedpath = "/account/forbidden";Options. Loginpath ="/home/login";        }); }

The code here means add authorization, add a cookie, configure the login page, and jump page without permission.

2. Find the Configure method and add the app. Useauthentication (), use authorization:

 Public void Configure (Iapplicationbuilder app, Ihostingenvironment env, Efcorecontext context)        {                       app. Useauthentication ();                   }

3. Create a new Controllerand add the method of login:

  Public AsyncTask<iactionresult>Login ([frombody] Sysuser sysuser) {//use EF to get users                varinfo = _context. Sysusers.where (m = m.username = = Sysuser.username && M.password = =Sysuser.password).                FirstOrDefault (); if(Info! =NULL)                {                        //Create an Identity certificate                    varClaims =NewList<claim>() {                    NewClaim (Claimtypes.sid,info. Id.tostring ()),//User ID                    NewClaim (Claimtypes.name,info. UserName)//User name                    }; varIdentity =NewClaimsidentity (Claims,"Testlogin"); varUserprincipal =NewClaimsPrincipal (identity); awaitHttpcontext.signinasync ("Mycookieauthenticationscheme", Userprincipal,Newauthenticationproperties {EXPIRESUTC= DateTime.UtcNow.AddMinutes ( -), Ispersistent=false, Allowrefresh=false                    }); returnJson (New{Success=true                    }); }                Else                {                    returnJson (New{Success=false, Message="Incorrect account name password! "                    }); }        }

From the above code, we come to the specific analysis.

The validation model for ASP. NET Core is claims-based authentication. Claim is a description of the characteristics of the subject being verified, such as: Login user name is Xxx,email xxx, where the "login user name", "email" is claimtype.

A group of claims constitute an identity, with these claims identity is claimsidentity

var claims = new List<claim> () {                    new Claim (Claimtypes.sid,info. Id.tostring ()),//user ID                    new Claim (Claimtypes.name,info. UserName)  //user name                    };                     var identity = new Claimsidentity (claims, "Login");

  

The owner of Claimsidentity is ClaimsPrincipal .

  var New ClaimsPrincipal (identity);

A claimsprincipal can hold multiple claimsidentity, such as a person who holds a driver's license and a passport.

var New ClaimsPrincipal (identity);                     await Httpcontext.signinasync ("mycookieauthenticationscheme"new  Authenticationproperties                    {                        = DateTime.UtcNow.AddMinutes (),                          False,                        false                    });

Understanding the three concepts of claim, claimsidentity and Claimsprincipal, you can understand why a login cookie is used before the code.

To use a cookie to represent a verified subject, must contain claim, claimsidentity, claimsprincipal The three information, Claimsprincipal is the person who holds the document, Claimsidentity is the document, " Login "is the type of document (this is assumed to be a driver's license) and claim is the information in the driver's license.

We need to verify the permissions on the action above [authorize], if there is no login status, will jump to the login page, how to configure the jump, has a variety of other configurations, see Startup.cs files,

 Public iactionresult Index ()        {// Fetch user information            var userId = User.findfirst (claimtypes.sid). Value;             var userName = User.Identity.Name;             return View ();        }

Why User.Identity.Name can take a username, let's look at the definition of user:

Yes, he's what we're talking about, Claimsprincipal.

At this time, I took out the identity card (claimsidentity), ID card has my name (claim)

4. Sign Out

Public async task<iactionresult> Logout ()        {            await Httpcontext.signoutasync (" Mycookieauthenticationscheme ");            Return redirecttoaction ("Index", "Home");        

 

ASP. NET Core series "four" based on claim login authorization

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.