asp.net MVC--using asp.net identity to implement claims-based authorization, advanced article __.net

Source: Internet
Author: User
Tags httpcontext static class

Read the catalogue into the world of the declaration create and use a declarative authorization to use a third party to authenticate the section

In this article, I will continue the ASP.net identity journey, which is also the last of the ASP.net identity trilogy. In this article, we will introduce the advanced features of ASP.net Identity, which support declarative and flexible use in conjunction with ASP.net MVC authorization, and support the use of third parties for authentication.

For a basic knowledge of asp.net Identity, please refer to the following article:

asp.net MVC--start using ASP.net Identity, introductory

asp.net MVC--Exploring ASP.net identity authentication and role-based authorization, intermediate

For an example of this article, you can download and preview here:

Click here to preview

Click here to download sample code back to top into the world of declarations

In an old user management system, such as an application that uses ASP.net membership, our application is considered to be the authoritative source for all of the user's information, so essentially the application can be considered a closed system that contains all the user information. In the previous article, I used asp.net identity to authenticate the credentials of the user stored in the database and authorize access based on the roles associated with those credentials, so the user information required for authentication and authorization in nature comes from our application.

asp.net Identity also supports the use of declarations to deal with users, and it works well, and applications are not the only source of user information, possibly from the outside, which is more flexible and convenient than traditional role authorization.

Next I'll show you how asp.net Identity supports claims-based authorization (claims-based authorization).

1. Understanding what is a declaration

A statement (claims) is a description of a user-related piece of information that includes the user's identity (such as name, Email, country, etc.) and role members, and it describes the type of information, the value, and the authentication side of the announcement. We can use declarations to implement claims-based authorization. Claims can be obtained from external systems and, of course, from the local user database.

For asp.net MVC applications, by customizing the Authorizeattribute, the declaration can be flexibly used to authorize access to the specified action method, unlike the traditional use of role authorizations, which is richer and more flexible based on declarative authorization, It allows user information to be used to drive authorized access.

since the declaration (Claim) is a description of the user's information, the simplest way to illustrate what is a declaration is to show it through concrete examples, which is more useful than the explanation of abstract concepts. So, I added a Controller named claims in the sample project, which is defined as follows: public class Claimscontroller:controller {    [ Authorize]     public ActionResult Index ()     {         claimsidentity claimsidentity = HttpContext.User.Identity as claimsidentity;         if (claimsidentity = = null)          {            return View ("Error", new String[] {"declaration not Found"});        &NBSP}         else          {             return View (claimsidentity.claims);        &NBSP}     }}

In this example, it can be seen that asp.net identity is well integrated into the ASP.net platform, while the HttpContext.User.Identity property returns the implementation of a IIdentity interface, and when the ASP.net identity When used in conjunction, the Claimsidentity object is returned.

The Claimsidentity class is defined under the System.Security.Claims namespace and contains the following important members:

Claims

Returns a collection of declared objects that the user contains

Addclaim (Claim)

Add a declaration to the user

Addclaims (claims)

Add a series of declarations to the user

Hasclaim (predicate)

Determines whether or not to include a declaration, and if so, returns True

Removeclaim (Claim)

To remove a declaration from a user

Of course there are more members in the Claimsidentity class, but the above table describes the members that are used very frequently in the Web application. In the preceding code, convert HttpContext.User.Identity to a Claimsidentity object and obtain all the user-related declarations through the object's claims property.

A declaration object represents a single piece of information data for the user, and the declared object contains the following attributes:

Issuer

Returns the name of the authenticating party providing the declaration

Subject

Returns the Claimidentity object that the declaration points to

Type

Returns the type of information the declaration represents

Value

Returns the value of the user information represented by the Declaration

With the basic concept of the Declaration, the view of the above code is modified to render all the user declaration information, and the corresponding view code looks like this: @using System.Security.Claims @using users.infrastructure @model ienumerable<claim> @{    viewbag.title = "Index";} <div class= "Panel Panel-primary" >     <div class= "panel-heading" >          statement     </div>     <table class= "Table table-striped" >          <tr>              <th>Subject</th>              <th>Issuer</th>              <th>Type</th>             <th >Value</th>         </tr>           @foreach (Claim Claim in Model.orderby (x=>x.type))         {             <tr>                  <td> @claim. Subject.name</td>                  <td> @claim. Issuer</td>                  <td> @Html. ClaimType (Claim. Type) </td>                  <td> @claim. Value</td>             </tr>          }     </table> </div>

The Type property of the claim object returns the URI Schema, which is not particularly useful for us, and the common Schema used as a value is defined in the System.Security.Claims.ClaimType class, so the output is more readable.     I added an HTML helper that was used to format Claim.type values: public static mvchtmlstring ClaimType (this htmlhelper HTML, string claimtype) { fieldinfo[] fields = typeof (Claimtypes).     GetFields (); foreach (FieldInfo field in fields) {if field. GetValue (NULL). ToString () = = ClaimType) {return new mvchtmlstring (field.         Name); Return to New Mvchtmlstring (string. Format (' {0} ', Claimtype.split ('/', '. '). Last ())); }

With the above infrastructure code, I request the index action under Claimscontroller to display all the statements associated with the user, as follows:

go back to the top Create and use the Declaration

For two reasons I find the statement interesting. The first reason is that applications can get declarations from multiple sources, rather than relying solely on local databases to get them. Later on, I'll show you how to use an external third-party system to authenticate users and create declarations, but at this point I add a class to simulate an internal system that provides declarations, naming it Locationclaimsprovider, as follows: public static class Locationclaimsprovider {    public static ienumerable<claim> GetClaims (ClaimsIdentity User)     {        List<Claim> claims=new List <Claim> ();         if (user. Name.tolower () = = "Admin")         {             claims. ADD (Createclaim (Claimtypes.postalcode, "DC 20500"));             claims. ADD (Createclaim (claimtypes.stateorprovince, "DC")); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         else          {       &Nbsp;    claims. ADD (Createclaim (Claimtypes.postalcode, "NY 10036"));             claims. ADD (Createclaim (claimtypes.stateorprovince, "NY"));         }         return claims; &NBSP;&NBSP;&NBSP;&NBSP}       private static Claim Createclaim (string type,string value) & nbsp;   {        return New Claim (type, value, Claimvaluetypes.string, "Remoteclaims"); &NBSP;&NBSP;&NBSP;&NBSP}}

in the preceding code, the Getclaims method accepts a parameter as a Claimsidentity object and creates a PostalCode and stateorprovince declaration for the user. In this class, suppose I simulate a system, such as a central human resource database, that would be the authoritative source of local information about the staff.

The declaration is added to the user in the authentication process, so the code is slightly modified at the Account/login action: [HttpPost] [allowanonymous] [Validateantiforgerytoken] public Async Task<actionresult> Login (Loginmodel model,string returnurl) {    if (ModelState.IsValid) & nbsp;   {        appuser user = await UserManager.FindAsync (model. Name, model. Password);         if (user==null)          {            modelstate.addmodelerror ("", " Invalid username or password "); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         else          {             var claimsidentity =                  await usermanager.createidentityasync (User, DefaultAuthenticationtypes.applicationcookie);            claimsidentity.addclaims (Locationclaimsprovider.getclaims (claimsidentity));Authmanager.signout ();             Authmanager.signin (new Authenticationproperties {ispersistent = false}, claimsidentity); Return Redirect (ReturnUrl);

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.