Webapi token, how the parameter signature is generated (reproduced)

Source: Internet
Author: User

API interface Security principles: 1. The identity of the caller 2. The request's uniqueness 3. The requested parameter cannot be tampered with 4. The requested validity time in the new interface development, there may be no such interface call security principle, but the common sense of experience tells us that each request should have the principle of security.

For example, this interface http://127.0.0.1/api/user/list?type=value this request to get the user list information can not be displayed directly in the Address bar input information (although a bit exaggerated, not puppy information so easy get it), The basic requirements for writing WEBAPI interfaces must ensure the security of the data and the validity of the request.

Here I use the token+ parameter signature + timestamp three system parameters to certify the validity of the request (Instant 100% request is valid, can not say 100% is also safe).

Name of parameter Must-Choose Type Role
Token Is String Caller ID to ensure that the identity is from the system certification, and effectively identify the user identity
Sign Is String Key,value of interface parameters to prevent tampering of parameter values and to prevent spoofing requests
Timestamp Is Int Time stamp to prevent replay attacks

So the question comes

How is 1.token generated? What is the role?

2. How are parameter signatures generated? What is the role?

3. What is the role of timestamps?

Read this article and you'll know. These three system parameters are how to ensure the validity of the request, to some extent, improve the security of the data

How is 1.token generated? What is the role? Token generation: The General API is basically divided into two kinds of client access APIs and tokens that require user login, here I say the latter, (simple popular practice) User login Input user name, password, access to the API, verify the database success. This time the token can be generated and the failure is returned directly. Here comes the question again! What is the way 1.token is generated? Where does 2.token exist? 3.token How to verify that you can obtain a unique user ID after verifying the data is successful (user name is also OK), take Username:zhanglin as an example, encrypt the identity (DES,MD5, other lines, critical data must be encrypted), This encrypted string can be used as a token. 2.token each request needs to be delivered, a cookie is recommended, or it can be persisted to the client. Now there is such an API interface http://127.0.0.1/api/user/list?token= Encryptusernamestr This encryptzhanglinstr is the login successful after the encrypted username returned to the client, the client with what to save here is not much introduced, just need to know to return to the client a user access token class can be, When the server-side method is validated, it is decrypted, gets to the string Zhanglin, and then compares this zhanglin with the system user (which can take the cache database, cache token value), if the comparison exists, it indicates that there is permission to access the API, and vice versa, the request is illegal. or code to implement it. The code is easy to understand, just to get this principle straight. [CSharp]View PlainCopy
  1. [Route ("login")]
  2. Public bool Login (string account, string pwd)
  3. {
  4. var obj = Db.dbUsers.FirstOrDefault (f = f.account = = Account && F.pwd = = PWD);
  5. if (obj! = null)
  6. {
  7. String token = account. Desencrypt (Deskey); //Encrypt to generate tokens,
  8. HttpCookie cookie = new HttpCookie (Cookietoken,token);
  9. HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (cookie); //Save Cookies
  10. return true;
  11. }
  12. Else
  13. {
  14. return false;
  15. }
  16. }
Tokens are generated after landing in a cookie based on the user's identity, so that each time the client sends a request, it will take the token, as follows: [CSharp]View PlainCopy
  1. [Route ("list"), HttpGet]
  2. Public list<string> List (string type,string token)
  3. {
  4. var obj = Db.dbUsers.FirstOrDefault (p = = P.account = token. Desdecrypt (Deskey));
  5. //Verify token
  6. if (obj! = null)
  7. {
  8. //Return Data set
  9. }
  10. Else
  11. {
  12. //Illegal request
  13. }
  14. }
3. This verifies that the token is correct and is generally cached. Token's role is to determine whether the request is issued by the system user, so as to effectively identify the requesting user's identity information 2. How are parameter signatures generated? What is the role? Parameter signature sign: In order to improve the process of communication, to prevent the parameter is maliciously modified, when the request interface with sign can effectively prevent the parameter tampering, then how does sign work? See how it's generated.   Such an interface http:127.0.0.1/api/product?&type=zl&p1=value1&p2=value2&p3=& Sign=signvalue First step: Stitching the parameter string, except the sign parameter itself and the null value of the P3, then the rest is the string type=zl&p1=value1&p2=value2, and then by the parameter name Fu Shen (descending) Order, Get the string P1=value1&p2=value2&type=zl the second step: then do the parameter name and value of the stitching, get the string p1value1p2value2type=zl, note the code, can not appear this &quot; , to transcode after "stitching the third step: the string to DES encryption, assuming that P1value1p2value2type=zl des encryption result is abc123, The resulting string abc123 is the value of the parameter sign Signvalue Fourth step: In the interface we will receive the parameter value abc123, and then decrypt to get the string P1value1p2value2type=zl, And the interface in the parameter stitching after the comparison, if not the same as the parameters of the sequence is different, the value of the parameter must have been modified. Summary: 1. The provider of the interface of the caller and the interface of the unified contract parameter encryption algorithm 2. The parameter signature is a record of the parameter key, value. If the parameter is modified, it must not be signed with the parameter, and the request  3 will not be called. What is the role of timestamps? In the API request interface, the time of the client request occurs is the timestamp, this parameter to the server, and the server-side time, if the time interval is not valid. In the development of ASP. Webapi interface, the MVC filter can be used to intercept the above three key parameters. The following code is implemented in. NET core, and the same approach is to intercept before entering the method, which is a login API. The return API result is a class ApiResult.cs, serialized as a JSON object that contains a successful OK method for two generic method requests, the error method for the request failed [CSharp]View PlainCopy
  1. Public class MyFilterAttribute:Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute
  2. {
  3. public override void OnActionExecuting (ActionExecutingContext context)
  4. {
  5. var Request_param = context. Actionarguments.values;
  6. var querycollection = context. HttpContext.Request.Query;
  7. String account = string.  Empty;
  8. String password = string.  Empty;
  9. long timespan = 0;
  10. string signature = string.  Empty;
  11. Try
  12. {
  13. account = Querycollection.where (p = = P.key = = "Account"). Select (f = f.value). FirstOrDefault ().  ToString ();
  14. Password = querycollection.where (p = = P.key = = "password"). Select (f = f.value). FirstOrDefault ().  ToString ();
  15. TimeSpan = long. Parse (querycollection.where (p = = P.key = = "TimeSpan"). Select (f = f.value). FirstOrDefault ().  ToString ());
  16. Signature = Querycollection.where (p = = P.key = = "signature"). Select (f = f.value). FirstOrDefault ().  ToString ();
  17. }
  18. catch (Exception ex)
  19. {
  20. var apiresult = apiresult<bool>. Error ("parameter exception" +ex.  ToString ());
  21. Context.  Result = new Jsonresult (Apiresult);
  22. }
  23. //var AccountName = context. routedata.values["AccountName"]. ToString ()
  24. var expires_minute = (timespan-datetime.now.ticks)/60000000000;
  25. if (expires_minute> 10| | EXPIRES_MINUTE<-10)
  26. {
  27. var Apimodel = apiresult<bool>.  Error ("Request timed out" +expires_minute);
  28. //var json = Jsonconvert.serializeobject (Apimodel);
  29. Jsonresult ret = new Jsonresult (Apimodel);
  30. Context. Result =ret;
  31. }
  32. var ok = ("account" + account + "password" + password). Contains (signature); //todo Encryption and decryption
  33. if (ok = = false)
  34. {
  35. var Apimodel = apiresult<bool>.  Error ("illegal request");
  36. var json = Jsonconvert.serializeobject (Apimodel);
  37. Jsonresult ret = new Jsonresult (Apimodel);
  38. Context. Result = ret;
  39. }
  40. base.  OnActionExecuting (context);
  41. }
  42. }

Zhang Lin
Original title: Webapi token, how the parameter signature is generated
Original link: http://blog.csdn.net/kebi007/article/details/72861532

Webapi token, how the parameter signature is generated (reproduced)

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.