A, Core authorization

A, Core authorization

Configuration

Open Startup.cs file in the project, find ConfigureServices way we normally do dependency injection configuration in which 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");
            });
}

About the meaning of this code is to add licensing support, and add a way to use Cookie, configuration and login page when the jump page does not have permission.

To find Configure method, add app.UseAuthentication (), license:

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

log in

Adding a Controller, such as AccountController, add a Action, such as Login, routing configured to correspond with the above configuration, the page will jump wrong when otherwise jump to log in.

User submits a user name and password, login code is 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 for user name and password is incorrect " ;
     return View ();
}

It should be noted here that  AuthenticationType  Scheme must be set the same as the previous configuration, so that the corresponding Registration Authority to take effect.

Second, use the login identity

Login directory, it is hoped can access resources only after some page or login. Use AuthorizeAttribute do restrictions. On the plus Controller needs to be done to limit the [Authorize] characteristics do limit.

[Authorize]
public class ThemeController
{
}

So that all of this under the Action Controller are only accessible after will need to log in. If you want some of Action can also be accessed without logging in, you can add an exception:

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

One of the most basic here login is complete.

In a Web project, often you encounter a problem, back-end and front-administrator user. These two users are available to log in the .net core 2.0, this will be very easy to implement.

Third, multi-user login

Add a login scheme (Scheme)

CookieAuthenticationDefaults.AuthenticationScheme, this is the system already defined a default login program, add a new identity to achieve a different login. code show as below:

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

Adding to use the new program, under 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 new login program and configure a new login page and login method is just the same, but AuthenticationType use the new program.

[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 for user name and password is incorrect " ;
     return View ();
}

Verify login status

Use and almost before, replaced by a new CustomerAuthorizeAttribute on the line

[CustomerAuthorize]
public class CustomerController
{
}

CustomerAuthorizeAttribute this class is not necessary, just to facilitate the use of written, in fact, can only define a new scheme (Scheme) on the line.

Who is HttpContext.User?

Log multiple users, then who is HttpContext.User it? If you have to use your Controller or Action the AuthorizeAttribute , that the use of the sign-on solution Attribute which is the HttpContext.User corresponding user login is that program. If no, then AddAuthentication () method by default it means that the user program (Scheme) is logged, is this a HttpContext.User.

 

 How to obtain the corresponding login user program it? Use HttpContext.AuthenticateAsync

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

sign out

This is simple to specify Quit it.

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

 

Guess you like

Origin www.cnblogs.com/fger/p/11947126.html