Asp. Net Core 2.0 Login authorization and multi-user login

Source: Internet
Author: User

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)        . Addcookie (Cookieauthenticationdefaults.authenticationscheme, o                = = {O.loginpath = new pathstring ("/ Account/login ");                O.accessdeniedpath = 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 Async Task <IActionResult> Login (string userName, string password, string ReturnUrl) {    var user = _userservice.login (userName, password);    if (user! = null)    {        user. AuthenticationType = Cookieauthenticationdefaults.authenticationscheme;        var identity = new Claimsidentity (user);        Identity. Addclaim (New Claim (claimtypes.name, user. UserID));        Await Httpcontext.signinasync (Cookieauthenticationdefaults.authenticationscheme, New ClaimsPrincipal (Identity));        if (Returnurl.isnullorempty ())        {            return redirecttoaction ("Index", "Dashboard");        }        Return Redirect (RETURNURL);    }    Viewbag.errormessage = "Login failed, user name password is incorrect";    return View ();}

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{Public    const string customerauthenticationscheme = " Customerauthenticationscheme ";    Public Customerauthorizeattribute ()    {this        . AuthenticationSchemes = Customerauthenticationscheme;    }}

Add using this new scenario under the Startup.cs file:

public void Configureservices (iservicecollection services) {    services. Addauthentication (Cookieauthenticationdefaults.authenticationscheme)        . Addcookie (Cookieauthenticationdefaults.authenticationscheme, o                = = {O.loginpath = new pathstring ("/ Account/login ");                O.accessdeniedpath = new PathString ("/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 Async Task <IActionResult> Login (string userName, string password, string ReturnUrl) {    var user = _userservice.login (userName, password);    if (user! = null)    {        customerauthorizeattribute.customerauthenticationscheme;        var identity = new Claimsidentity (user);        Identity. Addclaim (New Claim (claimtypes.name, user. UserID));        Await Httpcontext.signinasync (customerauthorizeattribute.customerauthenticationscheme, new ClaimsPrincipal (Identity));        if (Returnurl.isnullorempty ())        {            return redirecttoaction ("Index", "Dashboard");        }        Return Redirect (RETURNURL);    }    Viewbag.errormessage = "Login failed, user name password is incorrect";    return View ();}
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? 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 auth = 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 Redirect (ReturnUrl?? "~/");}

Original address: http://www.zkea.net/codesnippet/detail/post-60

Asp. Net Core 2.0 Login authorization and multi-user login

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.