asp.net core2.1 decrypt authentication and authorization

Source: https://www.cnblogs.com/pangjianxin/p/9372562.html

asp.net core2.1 decrypt authentication and authorization

This article translated from: https: //digitalmccullough.com/posts/aspnetcore-auth-system-demystified.html

Asp.net core2.0 paper provides an overview of how authentication and authorization system works, to give the reader a clearer explanation, it feels good, so the translation for your reference.

In front of a bunch of mentality and stop the annoying chatters, I do not turn up, start the text.

To understand this system first you need to understand its components and behavior. These components are split into identity, verbs (or actions), authentication handlers and middleware. I will explain one by one on each of the components there and prove how they work together in the latter instance. Because most of asp.net authentication handler core are Cookies auth handler, so this example uses cookie authentication.

Identity

To understand authentication (authentication) is how it works, then we must first understand the identity in asp.net core2.0 is a something. Sentence is to have three classes to represent a user's identity (identity): Claim, ClaimsIdentity and ClaimsPrincipal.

Claims

A Claim on behalf of a user's information points. It can be a user's last name, user name, user's home address, the user's age or other information about the user, in short, it is a point of information users. Claim a message can contain only one point.

There is a class in asp.net core2.0 in Claim. It is the most common constructor receives two strings, type, and value. Claim type parameter is the type or name, value is the value of user information in this Claim represent.

For example: The following code creates two Claim, wherein a type of "FullName", the value "Pangjianxin", another type ClaimTypes.Email, is [email protected] :

//This claim uses a standard string
new Claim("FullName","Dark Helmet");
//This claim type expands to 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'
new Claim(ClaimTypes.Email, "[email protected]");
// ClaimTypes which contains some default constants, used to facilitate the construction of Claim

ClaimsIdentity

An identity (Identity) on behalf of a form of identification, or put it another way, it is a way to prove who you are. In real life, an identity can be a driver's license, in asp.net core, which is a ClaimsIdentity class. This class represents a digital form of identity proof.

ClaimsIdentity a single instance can be certified (authenticated) can not be authenticated, according to Andrew Lock's talking about this in his article (https://andrewlock.net/introduction-to-authentication-with-asp-net -core /), is provided simply to look AuthenticationType attribute (as defined in ClaimsIdentity) may automatically ensure the IsAuthenticated (another attribute ClaimsIdentity inside, to determine whether authentication) attribute value is true. This is because if you can authenticate the identity (ClaimsIdentity) in any way, then it must have been certified (then it must, by definition, be authenticated.).

A stranger coming toward you and you want to somehow introduce himself, the stranger for you the equivalent of a non-certified CLaimsIdentity. Locke (the above-mentioned person, Lock) writes that this might be the guests of the cart (in real life, you may be able to add something to the shopping cart before landing), or other similar things useful. A driver's license contains many of the Claim: first name, last name, birthdate, and so on. Similarly, a ClaimsIdentity may also contain many Claim about the user.

ClaimsPrincipal

A body (Principal) represents a real user. It may contain one or more CLaimsIdentity, just like in real life a person can have a driver's license, Teacher, passport, etc. In addition, he also must have an ID card. Each document (ClaimsIdentity) for a different purpose and may contain a unique set of Claim. But all documents are different ways to prove the same person.

In conclusion, a CLaimsPrincipal on behalf of a user, it contains one or more ClaimsIdentity, ClaimsIdentity they represent a form of proof of identity, ClaimsIdentity but also contains one or more of Claim, Claim on behalf of a user's information points. ClaimsPrincipal is HttpContext.SiginAsync method (accurate, it is an extension method) parameter, and is transmitted to the inside AuthenticationHandler method.

Verbs

verb is a verb, or the command is called, behavior. In the authentication system asp.net core 2.0 (auth system) in a total of five verb it is invoked, and they are on the call order is not required. They are separate call, and there is no interaction between them, however, when used together, users can log in and access the page, or rejected. Here is a concise description of these five verb related duties, as well as later in the article detailed explanation:

Note: These are behaviors, not a method, but there are some ways to achieve the same naming these acts

Authenticate , Authentication

If present (such as a user's decoded Cookie), a user access to information.

Challenge

It requires the user to request certification process (such as display landing page)

SignIn

Persistent information about the user and placed somewhere (such as writing Cookie)

SignOut

Delete the user has persisted information (such as deleting Cookie)

Forbid

Contains two cases, one for the user is not authenticated, it prevents the user access to relevant resources, another case for certification but has enough authority (which relates to authorize athorization a) of the user (such as re directed to the "lack of authority" of the page).

Authentication Handlers

Authentication handlers (note the plural) is the real components of the above five kinds of operation. asp.net core provides default auth handler is Cookies authentication handler, this thing is to achieve the five actions described above. Note that, an auth handler does not have to implement all the above operation (to verb), e.g., Oauth handler (oauth an authorized protocol in .net core, the realization of source components of the agreement is identity server4, the Open Source Components while achieving openid connect, which is the authentication protocol built oauth basis) does not implement SignIn action, but pass the responsibility to another auth handler, such as cookie auth handler.

In order to use (schemes) and association and authentication scheme, authentication handler must be registered to the authentication system (auth system). A scheme is a string that identifies a unique auth handler in an authentication handler dictionary. For Cookies auth handler, the default scheme is "Cookies", but he can be replaced by any other string. Multiple authentication processing program may be used side by side, sometimes (as in the above-mentioned Oauth handler) other authentication processing program supplied.

Authentication Middleware

Middleware can be inserted into the pipe queue start, every http request from them have been. This article only interested in authentication middleware. These codes (authentication middleware) checks each request whether the user is authenticated, recall, the authentication operation to obtain the user information (from the cookie), but only under the presence of such information. When the request to initiate the authentication middleware calls the default program on behalf of the auth handler to perform authentication code. Auth handler return information to the authentication middleware, and then padding information to HttpContext.User above properties.

Authentication and Authorization Flow

In order to be able to successfully authenticate and authorize a user to access a resource, all of these components must be able to be used together in an authentication system. This process is initiated by a request for access to the protected (requires authorization) resources to start from a non-authenticated user.

The following shows a Cookie authentication routine:

1, the request reaches the server.

2, the authentication of the Authenticate middleware calls a method on the default handler and any useful information contained in the object to HttpContext.Use above.

3, the request reaches the top of the controller action.

4, if the action is not [the Authorize] decoration, directly by requesting the page and displays the corresponding end.

5, if the action is [the Authorize] modified, then the filter authorization (auth filter) checks whether the user has been authenticated before.

6, if the user does not have authentication, authorization filter (auth filter) performs a Challenge action, redirect to the appropriate login authentication page.

7, once the user has successfully redirected back after landing, filter checks whether authorized users are allowed (authorized) to access the relevant page.

8, if the user is allowed to access, on the display of the page, otherwise it will call Forbid action.

The sample code

This example does not intend to be a full-featured web applications. It uses a simple POCO class to store user names and passwords, in short, is simply to show the contents of this article, another matter. To illustrate this example is the certification process. Example deletes something and once independent.

Startup Class

When the application first starts it will trigger the startup class ConfigureService and Configure method. In aspnetcore2.0, authentication handler is configured ConfigureService process. And a method can be arranged on them by Configure method.

Copy the code
public void ConfigureServices(IServiceCollection services) {
    //Adds cookie middleware to the services collection and configures it
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => options.LoginPath = new PathString("/account/login"));

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    ...

    //Adds the authentication middleware to the pipeline
    app.UseAuthentication();

    ...
}
Copy the code

In ConfigureService method AddAuthentication method of authentication services (middleware?) Add to ServicesCollection above (DI system). And can be chained calls with a way to add to the authentication Cookie authentication handler middleware.

In the Configure method of adding authentication UseAuthentication call to the intermediate pipe, so that you can perform authentication of each request.

ApplicationUser class

Applications require a user class representative. . This simple class stores the user name and password.

Copy the code
public class ApplicationUser {
    public string UserName { get; set; }
    public string Password { get; set; }

    public ApplicationUser() { }
    public ApplicationUser(string username, string password) {
        this.UserName = username;
        this.Password = password;
    }
}
Copy the code

AccountController class

In order to use authentication middleware and handler in something meaningful, we covered some action. The following method of execution AccountController landing and logout methods. This class (AccountController) method call SiginAsync and SignoutAsync through some extension methods in order to perform the HttpContext class (with the specified or default handler) login and logout.

Copy the code
public class AccountController : Controller {
    //A very simplistic user store. This would normally be a database or similar.
    public List<ApplicationUser> Users => new List<ApplicationUser>() {
        new ApplicationUser { UserName = "darkhelmet", Password = "vespa" },
        new ApplicationUser{ UserName = "prezscroob", Password = "12345" }
    };

    public IActionResult Login(string returnUrl = null) {
        TempData["returnUrl"] = returnUrl;
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Login(ApplicationUser user, string returnUrl = null) {
        const string badUserNameOrPasswordMessage = "Username or password is incorrect.";
        if (user == null) {
            return BadRequest(badUserNameOrPasswordMessage);
        }
        var lookupUser = Users.FirstOrDefault(u => u.UserName == user.UserName);

        if (lookupUser?.Password != user.Password) {
            return BadRequest(badUserNameOrPasswordMessage);
        }

        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
        identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName));

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

        if(returnUrl == null) {
            returnUrl = TempData["returnUrl"]?.ToString();
        }

        if(returnUrl != null) {
            return Redirect(returnUrl);
        }
        
        return RedirectToAction(nameof(HomeController.Index), "Home");
    }

    public async Task<IActionResult> Logout() {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction(nameof(HomeController.Index), "Home");
    }
}
Copy the code

First, the class includes a list of users, Login method by the two overloaded, receiving a parameter of a returnUrl and stores it in TempData. The second method Login user login. The login method is a [HttpPost] modified method first checks to make sure the user login information entered is valid, if valid, he created a ClaimsIdentity. Receiving a set of attribute parameters AuthenticationType ClaimsIdentity class constructor, this parameter can be any string that represents the Identity been checked.

I just passed a certification scheme cookie because I am using cookie authentication. But you can set to any value to him. When using the logo later, I can use this property to determine if I Identity authentication method to authenticate the trust for.

var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName));

Then method calls HttpContext.SignInAsync (), a cookie and a certification scheme ClaimPrincipal passed.

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

Finally, the method determines the returnUrl, if returnUrl, it will redirect the user to returnUrl, if not, redirect to the home page.

Copy the code
if(returnUrl == null) {
    returnUrl = TempData["returnUrl"]?.ToString();
}
if(returnUrl != null) {
    return Redirect(returnUrl);
}

return RedirectToAction(nameof(HomeController.Index), "Home");
Copy the code

Login.cshtml

Create a Login page, corresponding to the login action Controller in.

Copy the code
@model ApplicationUser
@{
    <form asp-antiforgery="true" asp-controller="Account" asp-action="Login">
        User name: <input name="username" type="text" />
        Password: <input name="password" type="password" />
        <input name="submit" value="Login" type="submit" />
        <input type="hidden" name="returnUrl" value="@TempData["returnUrl"]" />
    </form>
}
Copy the code

HomeController类

在HomeController类中创建一个Members方法,加上[Authorize]标签

[Authorize]
public IActionResult Members() {
    return View();
}

[Authorize]特性会导致授权过滤器的调用。这个过滤器会决定用户是否已经登陆并且如果没有登陆会通过认证handler调用Challenge这个verb(动作),这个动作导致用户被要求登陆。

Members.cshtml

 接下来创建Members对应的视图:

Copy the code
@{
    ViewBag.Title = "Members Only";
}

<h2>@ViewBag.Title</h2>

<p>You must be a member. Congratulations, @User.Identity.Name, on your membership!</p>
Copy the code

_Layout.cshtml

Finally, one that allows users to click to landing or landing button is very useful.

@if(User.Identity.IsAuthenticated) {
    <li><a asp-area="" asp-controller="Account" asp-action="Logout">Logout</a></li>
} else {
    <li><a asp-area="" asp-controller="Account" asp-action="Login">Login</a></li>
}

in conclusion

Certification system is very interesting, the design is also very good. It is very scalable and easy to use custom authentication handler. Understand how the system work under the hood, the first step is to use it in addition to the default template. By using the component itself rather than relying on templates and convenient method, you can use a variety of custom authentication process. Now use it!

Guess you like

Origin www.cnblogs.com/frank0812/p/11846515.html