User login is a very common scenario. NET Core 2.0 's login style has changed a bit, and should be a benign change, becoming more convenient and easier to scale.
Configuration
Open the Startup.cs file in the project and find the configureservices method, which we usually do with dependency injection configuration in this method. Add the following code:
Public void configureservices (iservicecollection services) { services. Addauthentication (cookieauthenticationdefaults.authenticationscheme) = { new pathstring ("/account/login"); New PathString ("/error/forbidden");} );
The general meaning of this code is to add authorization support and add a way to use cookies to configure the login page and the jump page when no permissions are available.
Then find the Configure method and add the app. Useauthentication (), use authorization:
Public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { app. Useauthentication ();}
The basic configuration is complete.
Login
Add a controller, such as AccountController, and then add an action, such as login, to configure the route to correspond to the above configuration, or jump to the wrong page when you log in.
User submits user name and password, the login code is roughly as follows:
[HttpPost] Public AsyncTask <IActionResult> Login (stringUserName,stringPasswordstringReturnUrl) { varuser =_userservice.login (userName, password); if(User! =NULL) {User. AuthenticationType=Cookieauthenticationdefaults.authenticationscheme; varIdentity =Newclaimsidentity (user); Identity. Addclaim (NewClaim (claimtypes.name, user. UserID)); awaitHttpcontext.signinasync (Cookieauthenticationdefaults.authenticationscheme,NewClaimsPrincipal (identity)); if(Returnurl.isnullorempty ()) {returnRedirecttoaction ("Index","Dashboard"); } returnRedirect (RETURNURL); } viewbag.errormessage="Login failed with incorrect user name password"; returnView ();}
It is important to note that the scheme set by AuthenticationType must be the same as the previous configuration, so that the corresponding login authorization will take effect.
Using logon identities
The directory where you log in is that you want some pages or resources to be accessible only after you log in. Use Authorizeattribute to make restrictions. Add the [authorize] feature to the controller that needs to be limited.
[Authorize] Public class themecontroller{}
All actions under this controller must be logged in before they can be accessed. If you want some of these actions to be accessible without logging in, you can add exceptions:
[allowanonymous] Public ActionResult Index () { return View ();}
One of the most basic login is done here.
In Web projects, you typically encounter a problem with back-end administrators and foreground users. These two users are all logged in, and in. NET Core 2.0, this will be easy to implement.
Multi-User Login Add a login scheme (scheme)
Cookieauthenticationdefaults.authenticationscheme, which is a default login scheme already defined by the system, adds a new one to implement a different identity login. The code is as follows:
Public class customerauthorizeattribute:authorizeattribute{ publicconststring" customerauthenticationscheme"; Public Customerauthorizeattribute () { this. AuthenticationSchemes = customerauthenticationscheme; }}
Add using this new scenario under the Startup.cs file:
Public voidconfigureservices (iservicecollection services) {services. Addauthentication (Cookieauthenticationdefaults.authenticationscheme). Addcookie (Cookieauthenticationdefaults.authenticationscheme, O={O.loginpath=NewPathString ("/account/login"); O.accessdeniedpath=NewPathString ("/error/forbidden"); }) . Addcookie (customerauthorizeattribute.customerauthenticationscheme, option = = {option. Loginpath = new PathString ("/account/signin"); Option. Accessdeniedpath = new PathString ("/error/forbidden"); });}
Add a new login scheme and configure a new login page, log in the same way as just now, just AuthenticationType using the new scenario.
[HttpPost] Public AsyncTask <IActionResult> Login (stringUserName,stringPasswordstringReturnUrl) { varuser =_userservice.login (userName, password); if(User! =NULL) {User. AuthenticationType=Customerauthorizeattribute.customerauthenticationscheme; varIdentity =Newclaimsidentity (user); Identity. Addclaim (NewClaim (claimtypes.name, user. UserID)); awaitHttpcontext.signinasync (Customerauthorizeattribute.customerauthenticationscheme, NewClaimsPrincipal (identity)); if(Returnurl.isnullorempty ()) {returnRedirecttoaction ("Index","Dashboard"); } returnRedirect (RETURNURL); } viewbag.errormessage="Login failed with incorrect user name password"; returnView ();}
Verifying logon status
Use the same method as before, and replace it with a new customerauthorizeattribute:
[Customerauthorize] Public class customercontroller{}
Customerauthorizeattribute This class, is not required, just for ease of use and write, in fact, can simply define a new scheme (scheme) on the line.
Who is HttpContext.User?
Login to multiple users, then who is HttpContext.User? If you have a controller or action on the use of Authorizeattribute, that attribute use the login scheme, then this httpcontext.user corresponding to the program's login user. If it is not used, the Addauthentication () method defaults to the user who is logged in to its scheme (scheme), which is the HttpContext.User.
How do I get the login user for the corresponding scenario? Using Httpcontext.authenticateasync
var await Httpcontext.authenticateasync (customerauthorizeattribute.customerauthenticationscheme); if (auth. Succeeded) { auth. Principal.identity ...}
Sign Out
This is simple, specify the scheme to exit on it.
Public Async Task Logout (string returnurl) { await Httpcontext.signoutasync ( Cookieauthenticationdefaults.authenticationscheme); return " ~/ " );}
Original address: http://www.zkea.net/codesnippet/detail/post-60
Asp. Net Core 2.0 Login authorization and multi-user login