Ingenious, Webapi httpbasicauthorize the practice of building small cloud applications

Source: Internet
Author: User


HTTP uses basic authentication, and Webapi uses the [Httpbasicauthorize] tag controller to use Basic authentication. Basic authentication The disadvantage of HTTP Basic authentication is to provide simple user authentication function, its authentication process is simple and clear, suitable for the security requirements of the system or equipment, such as the configuration page of the routers used by everyone, almost all take this way. The disadvantage is that there is no flexible and reliable authentication strategy, such as the inability to provide domains (domain or realm) authentication capabilities, in addition, the BASE64 encryption strength is very low, can be said only to prevent Sohu search to find it. Of course, the HTTP Basic authentication system can also be combined with SSL or Kerberos to achieve a high security (relative) authentication system

A rare spit groove

Fled back to the second-tier Chengdu for two years has been doing leisure and entertainment industry's traditional management software, because the company's bosses too authoritarian, anyway, the share dividend hopeless, dry. As a total escape from the hometown of the county. Half a year has been doing a remote work, very grateful to the boss now, the source of my Home Office wish, although the income decline. But fortunately, the cost of living is much lower, that is, a mortgage and basic living expenses, two of the cost of a baby to go to school. There is a number of reverse telecommuting, recently finally have the time to realize their product dream. I want to do a set of general sales billing software, the prototype has been done 7788, that is, the architecture is single merchant, not multi-tenant. Now the plan is distributed Application architecture, sub-desktop terminal, Android, merchant platform side. Because of the previous period of time customers with the WEBAPI and socket server middleware in the ECS Cloud host is constantly attacked, once incredibly the middleware program to kill. So this time using WEBAPI need to consider the use of security protection mechanism. Because I am a personal project, too advanced security protection must also have a threshold. Borrowed from the UnionPay POS protocol, so began this practice.

Main validation process Design

1. Client Authenticationheadervalue the requested header

Client request, planning for App_id:token, as the following example is used on the server side of the "Request.Headers.Authorization.Parameter" to get this value, of course, it can not be plaintext, is simply handled with BASE64.

 using(varHttpClient =NewHttpClient ()) {                varCredentials = Convert.tobase64string (Encoding.ASCII.GetBytes (string. Format ("{0}:{1}","Datacool_winform","27c68f9a899842a598ddbacd2806fdd7"))); HttpClient.DefaultRequestHeaders.Authorization=NewAuthenticationheadervalue ("Basic", credentials); stringURL ="/ http"+ Middlewareip +": 5990"+"/api/cloudpos/getversion?k="+Guid.NewGuid ().                ToString (); Try                {                    stringRequestresult =httpclient.getstringasync (URL).                    Result; returnRequestresult; }                Catch(Exception ex) {Com.DataCool.DotNetExpand.LogHelper.Error (ex); return string.                Empty; }            }

2. Background points require authorization verification and 2 controllers that do not require authorization verification

For example, to apply for software trial, submit merchant store information, etc. is not required authentication can initiate the request, so need 2 controller

3. Background control and verify the App_id,token of the request header in the database

Backstage is to write a class implementation authorizeattribute, that is, "httpbasicauthorize" marked interception, the code is as follows:

public class Httpbasicauthorizeattribute:authorizeattribute {//<summary>//Check authorization </summary>//<param name= "Actioncontext" ></param> public override void Onautho            Rization (Httpactioncontext actioncontext) {if (actionContext.Request.Headers.Authorization! = null) {string[] Agent_info = Encoding.Default.GetString (convert.frombase64string (actioncontext.request.h Eaders. Authorization.parameter)). Split (":".                ToArray ()); Failure to follow the preset rules is also considered to be not authorized if (Agent_info.                    Length! = 2) {handleunauthorizedrequest (actioncontext);                Return } string request_agent = Agent_info.                FirstOrDefault (); String token = Agent_info.                LastOrDefault ();         #region Database checksum app_id and token using (var db = new pos_db ()) {try           {db.                    Database.createifnotexists (); The catch {} #region the default authorization if (!db.sys_api_authorize.                        Any ()) {var dt = DateTime.Now;                            var sys_scheme = new Sys_api_authorize {merchant_name = "Datacool",                            Request_scheme = "afeng124", Request_token = "15730052377", Master_key = Guid.NewGuid (). ToString ().                            Replace ("-", ""), Create_dt = dt, last_request_dt = DT,                        status = 1}; Db.sys_api_authorize.                        ADD (Sys_scheme); Db. Entry<sys_api_authorize> (Sys_scheme).                        state = System.Data.Entity.EntityState.Added; Db.                  SaveChanges ();  } #endregion var scheme_entity = db.sys_api_authorize .                                        Where (s = = S.request_scheme = Request_agent && S.request_token = = Token && S.status = = 1) .                    FirstOrDefault ();                        if (scheme_entity! = null) {Scheme_entity.last_request_dt = DateTime.Now; Db.                        SaveChanges ();                    IsAuthorized (Actioncontext);                    } else {handleunauthorizedrequest (actioncontext); }} #endregion} else {Handleunau            Thorizedrequest (Actioncontext); }}///<summary>//Failed to authenticate, log to record (originating the requested IP, method of request)///</summary>//&LT;PA Ram Name= "Actioncontext" ></param>        protected override void Handleunauthorizedrequest (Httpactioncontext actioncontext) {var challen            Gemessage = new Httpresponsemessage (System.Net.HttpStatusCode.Unauthorized);            CHALLENGEMESSAGE.HEADERS.ADD ("Www-authenticate", "Basic"); if (actionContext.Request.Headers.Authorization = = null) {String IP = ActionContext.Request.Get                Clientipaddress ();                var request_url = actionContext.Request.RequestUri.AbsoluteUri.ToString ();                     var request_obj = new {Requestip = IP, request_action = Request_url, Errordesc = ChallengeMessage.StatusCode.ToString (), Requestmethod = ACTIONCONTEXT.R Equest.                    Method.tostring (), Controller = ActionContext.ControllerContext.ControllerDescriptor.ControllerName,                Requesturl = actionContext.Request.RequestUri.AbsoluteUri.ToString ()};            Com.DataCool.DotNetExpand.LogHelper.Error (Request_obj); } base.             Handleunauthorizedrequest (Actioncontext);//throw New Httpresponseexception (challengemessage);}    }

Above if the direct throw will cause the host service program exception, did not expect to be directly to the parent class processing is OK.

The client call will have an exception if the authentication is not passed:

2016-10-09 17:02:39,916 Level: Error log Description: System.aggregateexception: One or more errors occurred. ---> System.Net.Http.HttpRequestException: The Response status code does not indicate success: 401 (Unauthorized).   ---The end of the inner exception stack trace---   in System.Threading.Tasks.Task.ThrowIfExceptional (Boolean includetaskcanceledexceptions)   in System.Threading.Tasks.Task ' 1.GetResultCore (Boolean waitcompletionnotification) in   System.Threading.Tasks.Task ' 1.get_result ()   in MiddlewareService.MiddlewareServiceSvr.HttpAPIRequest () Location D:\cloudservice\WebAPIService\MiddlewareServiceSvr.cs : Line Number---> (internal exception #0) System.Net.Http.HttpRequestException: The response status code does not indicate success: 401 (Unauthorized).

The browser simulates a get that looks like this:


4. The promotion method of the transformation software and the basic certification together

The main idea is this:

1. Before downloading the client software on the official website, the merchant applies for trial and submits the basic information of the merchant, which is the basis of marketing and pre-sale service.

2. After the merchant submits the trial application to download the desktop program, the desktop program activates the call API to get the master key and app_id and token.

3. Log in to the merchant background to set the store base parameters.

4. The server can control the usage period and function

Ingenious, Webapi httpbasicauthorize the practice of building small cloud applications

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: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: