WebAPI user authentication Tamper-proof Implementation (II) Absbaseauthenticationattribute

Source: Internet
Author: User

WEBAPI user authentication, like MVC, is verified by attribute, where an abstract base class is defined, and subclasses need to implement an abstract method of obtaining cooperative user information according to the cooperative number.

Absbaseauthenticationattribute

    Using System;    Using System.Web;    Using System.Collections.Specialized;    Using System.Net;    Using System.Net.Http;    Using System.Text.RegularExpressions;    Using System.Web.Http.Controllers;    Using System.Web.Http.Filters; <summary>//WEBAPI anti-tamper Signature validation abstract base class attribute///</summary> public abstract class Absbaseauthenticati         Onattribute:actionfilterattribute {//<summary>//Occurs before the action method is invoked. </summary>//<param name= "Actioncontext" >the action context</param> public O verride void onactionexecuting (Httpactioncontext actioncontext) {//Get the request var R for ASP. Equest = ((httpcontextwrapper) actioncontext.request.properties["Ms_httpcontext"]).            Request; NameValueCollection getcollection = Request. querystring;//this signature requires partner and sign to pass through QueryString if (getcollection! = null && getcollection.count > 0 )            {string partner = Getcollection[securitysignhelper.partner];                String sign = Getcollection[securitysignhelper.sign]; if (!string. Isnullorwhitespace (partner)//must include partner &&!string.                 Isnullorwhitespace (sign)//must include sign && regex.ismatch (sign, "^[0-9a-za-z]{32}$"))//sign must be a 32-bit MD5 summary                    {//Get partner corresponding Key//here for the time being only do a cooperative key check, do not do access check, if necessary, can be adjusted here, recommend RBAC String Partnerkey = this.                    Getpartnerkey (partner); if (!string.                        Isnullorwhitespace (Partnerkey)) {NameValueCollection postcollection = null; Switch (Request. Requesttype.toupper ()) {case "GET": break;//just to show restful four ways only this part is meaningless                    Code//The actual way in which the request should follow the RESTful standard case "POST":        Case ' PUT ': Case ' DELETE ': postcollection = Request.                            Form;//post data must pass the break through application/x-www-form-urlencoded way;                        Default:throw new NotImplementedException (); }//Get MD5 signature based on request data string vsign = Getcollection.getsecuritysign (partner, part                        Nerkey, postcollection); if (string.                            Equals (sign, vsign, stringcomparison.ordinalignorecase)) {//Validate pass, Execute base class method Base.                            OnActionExecuting (Actioncontext);                        Return }}}}//Here temporarily return with 401, can be adjusted for other return actioncontext.response =            ActionContext.Request.CreateResponse (httpstatuscode.unauthorized); Actioncontext.response = new Httpresponsemessage (httpstatuscode.unauthorized); }///<summary>///To get the cooperation key corresponding to the cooperation number, if not, return an empty string or null///</summary>//<para M name= "partner" ></param>///<returns></returns> protected abstract String Getpartnerk    EY (string partner); }

Sub-class example

    public class Authenticationattribute:absbaseauthenticationattribute    {        protected override string Getpartnerkey (string partner)        {            //todo: reads data from cache or elsewhere            return "BBB";}    }
You can actually add [authentication] on Apicontroller that require authentication, or you can write a base class, and then the Apicontroller that requires authentication inherits from that base class

    [Authentication]    public class Apicontrollerbase:apicontroller    {    }


WebAPI user authentication Tamper-proof Implementation (II) Absbaseauthenticationattribute

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.