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

User login is a very common application scenario. The login method of net core 2.0 has changed a bit, which should be a benign change, making it more convenient and easier to expand.

configure

Open the Startup.cs file in the project and find the ConfigureServices method. We usually do the configuration related to dependency injection 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, add the way to use cookies, configure the login page and the jump page without permission.

Find the Configure method again, add app.UseAuthentication(), and use authorization:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAuthentication();
}

This completes the basic configuration.

Log in

Add a Controller, such as AccountController, and then add an Action, such as Login. The configured route should correspond to the above configuration, otherwise, the wrong page will be jumped when jumping to login.

The user submits the username and password, and 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, username and password are incorrect";
    return View();
}

It should be noted here that  the Scheme set by AuthenticationType  must be the same as the previous configuration, so that the corresponding login authorization will take effect.

use login

The login directory is to hope that some pages or resources can only be accessed after login. Use AuthorizeAttribute to do restrictions. Add the [Authorize] attribute to the Controller that needs to be restricted to restrict.

[Authorize]
public class ThemeController
{
}

In this way, 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();
}

At this point, the most basic login is completed.

In a web project, there is often a problem with backend administrators and frontend users. Both users are loginable, in .net core 2.0 this will be easy to implement.

multi-user login

Add a login scheme (Scheme)

CookieAuthenticationDefaults.AuthenticationScheme, this is a default login scheme already defined by the system, add a new one to implement a different identity login. code show as below:

public class CustomerAuthorizeAttribute : AuthorizeAttribute
{
    public const string CustomerAuthenticationScheme = "CustomerAuthenticationScheme";
    public CustomerAuthorizeAttribute()
    {
        this.AuthenticationSchemes = CustomerAuthenticationScheme;
    }
}

Add to use 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. The login method is the same as before, but the AuthenticationType uses a new scheme.

[HttpPost]
public async Task <IActionResult> Login(string userName, string password, string ReturnUrl)
{
    var user = _userService.Login(userName, password);
    if (user != null)
    {

        user.AuthenticationType = 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 and password are incorrect";
    return View();
}

Verify login status

The usage method is similar to the previous one, just replace it with the new CustomerAuthorizeAttribute:

[CustomerAuthorize]
public class CustomerController
{
}

The CustomerAuthorizeAttribute class is not required, it is just written for convenience. In fact, it is entirely possible to define a new scheme (Scheme).

Who is HttpContext.User?

Multiple users are logged in, so who is HttpContext.User? If AuthorizeAttribute is used on your Controller or Action , which is the login scheme used by this Attribute, then this HttpContext.User corresponds to the login user of that scheme. If it is not used, the AddAuthentication() method defaults to the user logged in by its scheme (Scheme), which is the HttpContext.User.

How to get the login user of the corresponding plan? Use HttpContext.AuthenticateAsync

var auth = await HttpContext.AuthenticateAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme);
if (auth.Succeeded)
{
    auth.Principal.Identity...
}

sign out

This is simple, specify the program to exit.

public async Task Logout(string returnurl)
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Redirect(returnurl ?? "~/");
}

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325319713&siteId=291194637