Asp. Net Core 2.0 logon authorization and multi-user logon,. netcore

Source: Internet
Author: User

Asp. Net Core 2.0 logon authorization and multi-user logon,. netcore

User Login is a very common application scenario. net core 2.0 logon mode has changed. It should be a benign change, which makes it more convenient and easier to expand.

Configuration

Open the Startup. cs file in the project and findConfigureServicesMethod. We usually configure 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 following code adds authorization support and uses cookies to configure the logon page and jump to the page without permission.

FindConfigureMethod, add app. UseAuthentication (), use authorization:

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

This completes the basic configuration.

Login

Add a Controller, such as AccountController, and add another Action, such as Login. The configured route corresponds to the preceding configuration. Otherwise, an error page is displayed when you log on.

The user submits the user name and password. The logon 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 = cookieauthenticationults ults. authenticationScheme; var identity = new ClaimsIdentity (user); identity. addClaim (new Claim (ClaimTypes. name, user. userID); await HttpContext. signInAsync (cookieauthenticationults ults. authenticationScheme, new ClaimsPrincipal (identity); if (ReturnUrl. isNullOrEmpty () {return RedirectToAction ("Index", "Dashboard");} return Redirect (ReturnUrl);} ViewBag. errormessage = "Logon Failed, incorrect username and password"; return View ();}

Note thatAuthenticationTypeThe configured Scheme must be the same as the preceding configuration so that the corresponding logon authorization takes effect.

Use logon identity

To log on to a directory, you can only access some pages or resources after logon. UseAuthorizeAttribute. Add[Authorize]Feature.

[Authorize]public class ThemeController{}

In this way, all the actions under the Controller must be accessed after logon. If you want some of these actions to be accessible without logon, you can add the following exceptions:

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

Here, the most basic logon is complete.

In Web projects, there is usually a problem: backend administrators and front-end users. Both users can log on. net core 2.0, which is easy to implement.

Add a logon Scheme (Scheme) for multiple users)

CookieAuthenticationDefaults. AuthenticationScheme, which is a default logon scheme defined by the system. Add a new logon scheme to implement logon with different identities. The Code is as follows:

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

Add and 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 logon scheme and configure a new logon page.AuthenticationTypeA new solution is used.

[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 = "Logon Failed, incorrect username and password"; return View ();}
Verify logon 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, but is written for convenience. In fact, you can define only one new Scheme (Scheme.

Who is HttpContext. User?

Who is HttpContext. User after logging on to multiple users? By default, the AddAuthentication () method indicates the User logged on to the solution (Scheme), which is the HttpContext. User.

How do I obtain the login users of the corresponding solution? Use HttpContext. AuthenticateAsync

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

This is simple. You can exit the specified solution.

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

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

Related Article

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.