WEBAPI and mobile client communication security mechanism

Source: Internet
Author: User

WEBAPI and mobile client communication security mechanism

Recently the company has several projects need to develop mobile client, server-side selection Webapi, then how to ensure that the mobile phone client in the request server side of the data is not tampered with, how to ensure the failure mechanism of an HTTP request, the following summarizes our solution to these two problems in the project.

The basic ideas are as follows:

After the user successfully logged in to the app client, all HTTP requests sent by the mobile client to the server will have the following three parameters on the request header (Httpheader): 1, Uid (User ID), 2, Ts (timestamp), 3, sign (signature). Where TS is the current time minus the 10-bit time-stamp number obtained in 1970-1-1, sign is a string that is obtained after all HTTP request parameters and UID in the interface, TS is MD5 encrypted.

The implementation of the following (client implementation, the mobile phone client generates the following two parameters of the idea is the same):

1. TS Timestamp

TS parameter can guarantee the timeliness of the request, in the mobile phone client generated TS, on the server side to verify, the guarantee request is in our specified time period, the specific code is as follows:

(1), Generate TS (C #) code as follows, Andriod and iOS can be generated similarly

<summary>///Get 10-bit timestamp///</summary>//        <param name= "DT" ></param>        // <returns></returns> public        string Generatetimestamp (DateTime dt)        {            //Default Implementation of UNIX time of the current UTC time              TimeSpan ts = dt. ToUniversalTime ()-New DateTime (1970, 1, 1, 0, 0, 0, 0);            Return Convert.toint64 (TS. totalseconds). ToString ();        }  

(2), Server end-to-end authentication TS code as follows, we specify from the mobile phone client to the server side of the request is valid for 5 minutes, timestamp parameters are followed in the HTTP request header

Get request header information            var requestheader = HttpContext.Current.Request.Headers;                       10-bit timestamp            var ts = requestheader.get ("ts");            Verify that TS is legal (Request time valid: plus minus 5 minutes)            var ts = TS;//10 bit timestamp            if (ts. Length = ten)            {                var resp = request.createresponse<string> (Httpstatuscode.ok, "Request Expired", "Application/json "); ;                throw new Httpresponseexception (RESP);            }            var tsdate = comhelper.convertintdatetime (ts. ToString ());            if (Tsdate > DateTime.Now.AddMinutes (5) | | Tsdate < DateTime.Now.AddMinutes ( -5))            {                var resp = Request.createresponse<string> (Httpstatuscode.ok, "Request Expired", "Application/json");;                throw new Httpresponseexception (RESP);            }

(3), Comhelper public class code is as follows

Comhelper

2. Sign Signature

(1), sign generation rules: Server-side interface of all parameters +uid+ts, to remove the parameters of the parameter value is null, sorted by the parameter key value, with & Link, and all converted to lowercase, and then with MD5 encryption, through Httpheader sent to the server-side interface.

Generate the sign big code as follows (C #), Android and iOS can be generated similarly

If the mobile client request an API interface: Http://weapi.com/order/getlist? STATUSID=1&CARID=2&CITYID=3&NAME=&KEY=222SIGN=MD5 (carid=2&cityid=3&key=222& STATUSID=1&TS=0123456789&UID=110)

(2), verify the client's sign to prevent the parameter from being modified

Request signature, Client generated signature            var = requestheader.get ("sign");//Sort dictionary, sort by key            sorteddictionary<string, string> Postvalue = null;            Gets all the parameters in the request            Postvalue = Comhelper.getrequestsortdic (true);            Postvalue.add ("UID", UID);//api account name            postvalue.add ("ts", TS);//10-bit timestamp             string apiprivatekey = " 2d7e7c96-dac5-4526-96c3-c60cdec4b120 ";//client and phone side consistent            //server-side generated sign            string mysign = Comhelper.getresponsemysign (Postvalue, apiprivatekey);            if (! Sign.equals (MySign, stringcomparison.invariantcultureignorecase))            {                var resp = request.createresponse <string> (Httpstatuscode.ok, "signature error", "Application/json");;                throw new Httpresponseexception (RESP);            }

3. Simulation Test

(1) C # simulates an HTTP request with the following code

 The requested API address string url = "Http://localhost:51942/api/Values/Get?"            statusid=1&carid=2&cityid=3&name=&key=1233 ";            Generate TS String ts = Comhelper.generatetimestamp (DateTime.Now); SortedDictionary automatically sorts sorteddictionary<string by key value, string> sortdic = new sorteddictionary<string,            String> ();            Sortdic.add ("Statusid", "1");            Sortdic.add ("Carid", "2");            Sortdic.add ("Cityid", "3");            Sortdic.add ("name", "");            Sortdic.add ("Key", "1233");            Sortdic.add ("Uid", "110");            Sortdic.add ("ts", TS);            String apiprivatekey = "2d7e7c96-dac5-4526-96c3-c60cdec4b120";//client and phone side consistent, MD5 encryption more use a parameter//Get sign signature                        String sign = Comhelper.getresponsemysign (Sortdic, Apiprivatekey);            Send request System.Net.WebRequest WReq = System.Net.WebRequest.Create (URL);            WREQ.HEADERS.ADD ("Uid", "110"); Wreq.headERs.            ADD ("ts", TS);            WREQ.HEADERS.ADD ("sign", sign);            System.Net.WebResponse Wresp = Wreq.getresponse ();            System.IO.Stream Respstream = Wresp.getresponsestream ();                using (System.IO.StreamReader reader = new System.IO.StreamReader (Respstream, Encoding.UTF8)) { String res= Reader.            ReadToEnd (); }

(2) server-side validation parameters, parameter validation written in the BaseApiController.cs file, as long as the inheritance of the class can verify the parameters passed by the client

public class Valuescontroller:baseapicontroller    {                //Get api/values public        ienumerable<string> get (String statusid,string carid,string cityid,string name, string key)        {            return new string[] {"value1", "value2"};        }

Baseapicontroller

Everyone can add my qq:530439142, together with the growth of communication

WEBAPI and mobile client communication security mechanismeric.chen 2015-10-20 18:23 read: 758 comments: 7WEBAPI Service Monitoringeric.chen 2015-01-22 11:28 read: 1553 comments: 2WebAPI automatically generate help documentseric.chen 2014-08-22 10:50 read: 1256 comments: 4Mvc4+webapi+redis Session sharing exercise (bottom)eric.chen 2013-08-09 21:49 read: 2156 comments: 1Mvc4+webapi+redis Session sharing exercise (top)eric.chen 2013-08-08 20:41 read: 3992 comments:

WEBAPI and mobile client communication security mechanism

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.