WEBAPI Framework Building-security mechanism (iii)-Role-based rights control

Source: Internet
Author: User

Webapi Frame Building Series Blog

The previous article has completed the "authentication", if just want to simply implement role-based rights management, we basically do not write code, Microsoft has provided the authorize features, directly with the line.

How to use authorize properties

Configure authorize

Simple, directly on the code

Using system.collections.generic;using system.net.http;using system.security.claims;using System.Web.Http;using Webapi.    Common;namespace webapi.example{[Routeprefix ("api/security")] public class Securitytestcontroller:apicontroller {//<summary>/////////////<returns></ returns> [Route ("token"), HttpGet] public ihttpactionresult GetToken () {var dic=new dic            Tionary<string,object> (); foreach (Var querynamevaluepair in Request.getquerynamevaluepairs ()) {dic.            ADD (Querynamevaluepair.key,querynamevaluepair.value); } var token=new jwthelper ().            Encode (DIC, "Shengyu", 30);        return Ok (token); }///<summary>//Return the encrypted information in token///</summary>//&LT;RETURNS&GT;&LT;/RETURNS&G        T [Route ("Getuserinfofromtoken"), HttpGet] public ihttpactionresultGetUser () {var user = (ClaimsPrincipal) user;            var dic=new dictionary<string,object> (); foreach (var userclaim in user. Claims) {dic.            ADD (Userclaim.type,userclaim.value);        } return Ok (DIC);        } #region a hard-coded way to implement simple permissions control//<summary>//or only users of a certain role have access to//</summary>        <returns></returns> [Route ("Bycode/onlyroles"), authorize (Roles = "Admin,superadmin"), HttpGet]        Public Ihttpactionresult Onlyroles_setbycode () {return ok ("Onlyroles_setbycode, only Administrators can access"); }///<summary>///Only a few users have access to//</summary>//&LT;RETURNS&GT;&LT;/RETURNS&G        T        [Route ("Bycode/onlyusers"), authorize (Users = "Zhang San, John Doe"), HttpGet] public ihttpactionresult onlyusers_setbycode ()        {return ok ("Onlyroles_setbycode, only Zhang San and John Doe to access");   } #endregion} } 

The authorize feature has roles and users two properties, sets the values of these two properties, and controls which roles/users have access to them. The authorize attribute can be used to modify a class or method, and if the entire controller is to be controlled with permissions, the controller class is decorated, otherwise it is only decorated on an interface. if the controller is decorated but also excludes an action, the AllowAnonymous feature can be used to exclude it.

Get token

Now get a token that contains a "role for admin" message, as follows

Use previous article: Webapi frame Building-security mechanism-authentication (ii) Get token in the interface get a role for admin token

Request an interface that requires permissions

The request requires a role of admin or Superadmin interface Securitytestcontroller.onlyroles_setbycode (), notice that the token generated in the previous step is placed in the HTTP In the header of request

You can try to generate tokens for a non-admin role in the "Get token" step, then there will be an authorization failure error in this step, such as

Similarly, when the user is set to "Zhang San" or "John Doe" in the "Get token" step, the Securitytestcontroller.onlyusers_setbycode () interface can be accessed with this token.

  In the actual development, the interface to obtain tokens (that is, Method Securitytestcontroller.gettoken ()) in the code is usually written in the user login interface, the user through the user name and password login successfully, the interface to access a token to the client, Each interface request from the client will be headers with this token. The default authorize feature provided by Microsoft is sufficient for small projects and medium-sized projects that have no complex requirements for permission control. The disadvantage is that the various roles of the business must be determined before the project is developed because it is written in a "hard-coded" way on the interface method. Later, if you want to modify the role of an interface, only re-modify the code.

If you want to achieve more controllable role-based permission control, only write authorize filter yourself. The following describes how to write your own authorize filter.

Custom Authorize Filter

You can write your own authorize filter by inheriting one of the following three objects

namely: Authorizeattribute,Authorizationfilterattribute,Iauthorizationfilter, the relationship between the three

I take the inheritance authorizeattribute, and rewrite the IsAuthorized method, the code is as follows

Using system.net;using system.net.http;using system.web.http;using system.web.http.controllers;namespace webapi. security{    //<summary>//Role Basic Authorizeattribute (roles-based authorization)///    </summary>    public class Rbauthorizeattribute:authorizeattribute    {        protected override bool IsAuthorized ( Httpactioncontext actioncontext)        {            //under can replace your own authorization logic code            return base. IsAuthorized (Actioncontext);        }        protected override void Handleunauthorizedrequest (Httpactioncontext actioncontext)        {             Actioncontext.response =                ActionContext.ControllerContext.Request.CreateErrorResponse ( Httpstatuscode.unauthorized, "Unauthorized");}}}    

The Rbauthorize feature and authorize feature usage are the same, and no longer repeat. Subsequent blogs introduce role-based rights management table structures and write authorization logic in the IsAuthorized method.

WEBAPI Framework Building-security mechanism (iii)-Role-based rights control

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.