Asp. Net Core 2.0 logon authorization and multiple user logins

Source: Internet
Author: User

User login is a very common application scenario. NET Core 2.0 login mode has changed a bit, should be a benign change, become more convenient, easier to expand. Configuration

Open the Startup.cs file in the project and find the configureservices method, where we usually do dependency injection configuration. 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 without permission.

Then find the Configure method and add the app. Useauthentication (), use authorization:

public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory)
{
    app . Useauthentication ();
}

So the basic configuration is complete. Log in

Add a controller, such as AccountController, and add an action, such as login, configured routing, to correspond to the above configuration, or jump login will skip the wrong page.

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 = _us Erservice.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, username password incorrect";
    return View ();
}

Note here that the scheme set by AuthenticationType must be the same as the previous configuration, so that the corresponding login authorization will not take effect. Using logon Identities

A directory where 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 you want to restrict.

[Authorize]
public class Themecontroller
{
}

All the action under this controller must be logged in to access it. If you want some of these action to be accessible without logging on, you can add an exception:

[AllowAnonymous]
Public ActionResult Index ()
{return
    View ();
}

Here is a very basic login to complete.

In a Web project, you typically encounter a problem, back-end administrators, and foreground users. All two users are logged in, and in. NET Core 2.0, this will be easy to implement. Multi-User login Add a login scheme (scheme)

Cookieauthenticationdefaults.authenticationscheme, this is the system has defined a default login scheme, add a new 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 the use of this new scheme 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 to log in the same way as just now, just AuthenticationType using the new scheme.

[HttpPost]
Public async Task <IActionResult> Login (string userName, string password, string returnurl)
{
    var user = _us Erservice.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, username password incorrect";
    return View ();
}
Verifying logon status

Using the same method as before, replace it with a new customerauthorizeattribute:

[Customerauthorize]
public class Customercontroller
{
}

Customerauthorizeattribute This class, is not required, but for the convenience of writing, in fact, can only define a new scheme (scheme) on the line. who is HttpContext.User.

Login to multiple users, then who is HttpContext.User it. The Addauthentication () method defaults to the user whose scheme (scheme) is logged on, which is the HttpContext.User.

How to obtain the corresponding scheme of the logged-in user? Using Httpcontext.authenticateasync

var auth = await httpcontext.authenticateasync (customerauthorizeattribute.customerauthenticationscheme);
if (auth. Succeeded)
{
    auth. Principal.identity ...
}
Exit Login

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

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.