Web API series (ii) interface security and parameter verification, webapi

Source: Internet
Author: User

Web API series (ii) interface security and parameter verification, webapi

I have briefly introduced the design of web APIs before, but many people have asked me how to design and implement web APIs reasonably. For example, interface security, exception handling, and unified data return. Therefore, it is necessary to systematically summarize the Design and Implementation of web APIs. As we have already introduced the design of web api parameters and return formats, Web API series (I) Design Experience and summary. This time, let's talk about interface security.


Because Web API is an Internet-based application, the security is much stricter than accessing the database locally. Generally, the common practice is to use several steps to ensure interface and data security:

1. First, data is transmitted over HTTPS Based on the CA certificate to prevent data eavesdropping;

2. The parameter-encrypted signature is then used for transmission. An encrypted signature is added to the passed parameter to verify the signature content on the server side to prevent tampering;

3. Generally, access through interfaces must be verified using tokens of user identities. Data access is allowed only when the check is passed.


Web API access methods can be divided into several categories:

1) Use the user name and password. This method is relatively simple and can effectively identify a user (such as user information, passwords, or related interface permissions ). After the verification is successful, related data is returned.

2) use a secure signature. For the data submitted in this way, the signature parameters of the URL Connection are encrypted by a certain security rule. After the server receives the data, it is also encrypted by the same rule. After confirming that the data has not been tampered with halfway, then, modify the data. Therefore, we can specify different encryption keys for different clients, such as Web/APP/Winfrom, and other access methods. However, the keys are agreed by both parties and are not transmitted over network connections, generally, the connected AppID is used for connection transmission. The server uses this AppID to encrypt and compare signature parameters. Currently, this is the background callback processing mechanism.

3) Public interface calls do not require the User Token to be passed in or encrypted signature to parameters. This type of interface is generally less, but only provides some common data display.


Web api security verification

The implementation of username and password is relatively simple, so it is not described here. Let's talk about the implementation of secure signatures. Because Web API calls are all stateless, all interface requests must contain a secure signature.



Core security verification code snippet of web api:

Public class QueryData {public QueryData () {} public QueryData (IEnumerable <KeyValuePair <string, string> paramList) {// TODO: complete member initialization try {if (paramList = null) {throw new Exception ("the request parameter is blank! ");} Foreach (var param in paramList) {m_values [param. key] = param. value; //} catch (Exception ex) {throw new Exception (ex. message) ;}} // the advantage of sorting the Dictionary is that it is convenient to sign the data packet, and you do not need to sort the private SortedDictionary again before signing. <string, object> m_values = new SortedDictionary <string, object> (); /*** set the value of a field * @ param key field name * @ param value Field value */public void SetValue (string key, object value) {m_values [key] = v Alue;}/*** obtain the value of a field based on the field name * @ param key field name * @ return key corresponds to the field value */public object GetValue (string key) {object o = null; m_values.TryGetValue (key, out o); return o ;} /*** determine whether a field has been set * @ param key field name * @ return if the field key has been set, true is returned, otherwise, false */public bool IsSet (string key) {object o = null; m_values.TryGetValue (key, out o); if (null! = O) return true; else return false;} public string ToUrl () {string buff = ""; foreach (KeyValuePair <string, object> pair in m_values) {if (pair. value = null) {throw new Exception ("contains a field with a null Value! ");} If (pair. Key! = "Sign" & pair. Value. ToString ()! = "") {Buff + = pair. key + "=" + pair. value + "&" ;}} buff = buff. trim ('&'); return buff;} public string MakeSign (string appKey = "test") {// convert the url Format string str = ToUrl (); // Add api key str + = "& key =" + appKey; // MD5 encryption var md5 = MD5.Create (); var bs = md5.ComputeHash (Encoding. UTF8.GetBytes (str); var sb = new StringBuilder (); foreach (byte B in bs) {sb. append (B. toString ("x2");} // convert all characters to uppercase Return sb. ToString (). ToUpper ();} public bool CheckSign () {// skip if (! IsSet ("sign") {throw new Exception ("the signature exists but is invalid! ");} // If the signature is set but the signature is empty, an exception else if (GetValue (" sign ") = null | GetValue (" sign ") is thrown "). toString () = "") {throw new Exception ("the signature exists but is invalid! ");} // Obtain the Received Signature string return_sign = GetValue (" sign "). toString (); // calculate the new signature locally string cal_sign = MakeSign (); if (cal_sign = return_sign) {return true;} return false ;}}

Code is for your reference and learning. Formal projects can be designed according to your company's needs. In the future, the complete source code of relevant open-source projects will also be available.


Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

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.