How to Write secure API interfaces (parameter encryption + timeout processing + private key verification + Https)-continued (with demo), apidemo

Source: Internet
Author: User

How to Write secure API interfaces (parameter encryption + timeout processing + private key verification + Https)-continued (with demo), apidemo

In the previous article, we talked about the design philosophy of interface security. If you haven't seen the previous blog, I suggest you read it later.

Through discussion by the school friends, and I checked some information myself, and then made a relatively complete summary of interface security, and promised to write a demo for everyone, which will be released today.

Security is also relative. Next I will analyze the security level

 

1. Fully open interfaces

There is no such interface that anyone can call and anyone can access. It is not limited by the time space. It can be called as long as it can be connected to the Internet, and there is no security at all.

To be honest, we are always in touch with such interfaces every day. You are checking the express delivery, you are checking the weather forecast, you are checking the plane, train flights, etc. These are all public interfaces.

I call this the streaking age. The Code is as follows:

/// <Summary> /// interface made public to the public /// </summary> /// <returns> </returns> [HttpGet] [Route ("NoSecure")] public HttpResponseMessage NoSecure (int age) {var result = new ResultModel <object> () {ReturnCode = 0, Message = string. empty, Result = string. empty}; var dataResult = stulist. where (T => T. age = age ). toList (); result. result = dataResult; return GetHttpResponseMessage (result );}View Code

 

2. interface parameter encryption (basic encryption)

You write an interface. You only want to use it for specific callers. You call these callers to a small room and announce to them that I only want to use this interface for you, I will give each of you a key. You can just hold it when you use it.

The key is the parameter encryption rule I mentioned above, which can be called with this rule.

This is a security issue. If one of these Members accidentally loses the key or is stolen, can the person who has the key still use the interface? In addition, he can copy many keys for unknown users.

It is equivalent that someone gets your request link. If the business does not judge the uniqueness of the Link (in fact, the business logic usually does not record the encrypted signature of each request, so it does not make a uniqueness Judgment ), it will be called repeatedly. There are certain security vulnerabilities. How can this problem be solved? Let's take a look at the code for this scenario first, and then proceed!

/// <Summary> /// interface encryption /// </summary> /// <returns> </returns> [HttpGet] [Route ("SecureBySign")] public HttpResponseMessage SecureBySign ([FromUri] int age, long _ timestamp, string appKey, string _ sign) {var result = new ResultModel <object> () {ReturnCode = 0, message = string. empty, Result = string. empty };# region verify whether the signature is valid var param = new SortedDictionary <string, string> (new AsciiComparer (); param . Add ("age", age. toString (); param. add ("appKey", appKey); param. add ("_ timestamp", _ timestamp. toString (); string currentSign = SignHelper. getSign (param, appKey); if (_ sign! = CurrentSign) {result. returnCode =-2; result. message = "invalid signature"; return GetHttpResponseMessage (result) ;}# endregion var dataResult = stulist. where (T => T. age = age ). toList (); result. result = dataResult; return GetHttpResponseMessage (result );}View Code

 

3. interface parameter encryption + Interface timeliness verification (this level is generally very secure)

After the previous step, you found someone who was not clear enough to call your interface. You were so upset that you immediately called the person who really needed to call the interface and told them to change the key for them every day. As usual, the keys of some partners have been stolen by thieves, who have been painstaking. After several days of observation, they are ready to work on a dark night. Taking out the key for a long time cannot open your Holy Door, because thieves do not know that you are changing the key every day.

The thief was not satisfied. After a period of time, he discovered the rule of Changing keys. After obtaining the key, I started it on that day without thinking about it, because he knew that the key in his hand expired the next day after you changed the key.

As a result, the thief wished. How can this problem be solved? Let's take a look at the code for this scenario first, and then proceed!

/// <Summary> /// the interface is encrypted and the validity is determined based on the timestamp /// </summary> /// <returns> </returns> [HttpGet] [Route ("SecureBySign/Expired")] public HttpResponseMessage SecureBySign_Expired ([FromUri] int age, long _ timestamp, string appKey, string _ sign) {var result = new ResultModel <object> () {ReturnCode = 0, message = string. empty, Result = string. empty}; # region determines whether the request has expired-assuming that the expiration time is 20 seconds DateTime requestTime = GetDateTimeBy Ticks (_ timestamp); if (requestTime. addSeconds (20) <DateTime. now) {result. returnCode =-1; result. message = "interface expired"; return GetHttpResponseMessage (result) ;}# endregion # region verify whether the signature is valid var param = new SortedDictionary <string, string> (new AsciiComparer ()); param. add ("age", age. toString (); param. add ("appKey", appKey); param. add ("_ timestamp", _ timestamp. toString (); string currentSign = SignHelper. GetSign (param, appKey); if (_ sign! = CurrentSign) {result. returnCode =-2; result. message = "invalid signature"; return GetHttpResponseMessage (result) ;}# endregion var dataResult = stulist. where (T => T. age = age ). toList (); result. result = dataResult; return GetHttpResponseMessage (result );}View Code

 

4. interface parameter encryption + timeliness verification + private key (to achieve this level of security is solid)

After the previous step, you found that there was still a theft. What should we do? You plan to give everyone a dark sign based on a key. Even if the key has been acquired by a thief and the thief has no dark signs, you can't do it, in this way, it is easy to locate the problem of leakage of the hidden signs. To find the root cause of the problem, you only need to change the key for the current person.

But this is not foolproof, because the key may be obtained by thieves after all. The Code is as follows:

/// <Summary> /// the interface is encrypted and the validity is determined based on the timestamp and the private key is used for verification. /// </summary> /// <returns> </returns> [httpGet] [Route ("SecureBySign/Expired/KeySecret")] public HttpResponseMessage SecureBySign_Expired_KeySecret ([FromUri] int age, long _ timestamp, string appKey, string _ sign) {// key set, here, let's just get two test data. // if there are many callers, You need to review the authorization and generate a key based on certain rules to store the data in the database. If the function is extended, you can perform different function permission management for different callers // Dynamically Retrieve the function permission from the library when calling an interface. Each caller carries his or her key when calling the interface, the caller generally places his/her key on the website. Configure Dictionary <string, string> keySecretDic = new Dictionary <string, string> (); keySecretDic. add ("key_zhangsan", "D9U7YY5D7FF2748AED89E90HJ88881E6"); // three keys, keySecretDic. add ("key_lisi", "I9O6ZZ3D7FF2748AED89E90ZB7732M9"); // key var result = new ResultModel <object> () {ReturnCode = 0, Message = string. empty, Result = string. empty}; # region determine whether the request has expired --- assume that the expiration time is 20 seconds DateTime requestTime = GetDateTi MeByTicks (_ timestamp); if (requestTime. addSeconds (20) <DateTime. now) {result. returnCode =-1; result. message = "interface expired"; return GetHttpResponseMessage (result) ;}# endregion # region obtains the key value string secret = keySecretDic Based on appkey. where (T => T. key = appKey ). firstOrDefault (). value; # endregion # region check whether the signature is valid var param = new SortedDictionary <string, string> (new AsciiComparer (); param. add ("age", age. toS Tring (); param. add ("appKey", appKey); param. add ("appSecret", secret); // Add the secret to encrypt the param. add ("_ timestamp", _ timestamp. toString (); string currentSign = SignHelper. getSign (param, appKey); if (_ sign! = CurrentSign) {result. returnCode =-2; result. message = "invalid signature"; return GetHttpResponseMessage (result) ;}# endregion var dataResult = stulist. where (T => T. age = age ). toList (); result. result = dataResult; return GetHttpResponseMessage (result );}View Code

 

5. interface parameter encryption + timeliness verification + Private Key + Https (I call this level a Golden Bell Hood, which is the safest in the world)

After the previous step, we changed the transmission mechanism to Https, and the thief was absolutely forced. So what about Https? You can build a local environment, refer to this article: http://www.cnblogs.com/naniannayue/archive/2012/11/19/2776948.html

 

In addition, the interface in this article is written using the MVC WebAPI, fully based on the RESTful standard. If this is not a special understanding can refer to this article: http://www.cnblogs.com/landeanfen/p/5501490.html

 

Complete demo download

 

Note: The demo cannot be run directly. You need to configure two web projects in iis. The api represents the interface provider, and its main domain must be configured in webconfig of business, in the address bar of the browser, request each call interface method in business to call the interface.

1. If you want to verify that the parameter is incorrect, you need to set a breakpoint to retrieve the interface url, tamper with the url parameter, and then simulate the request in the browser.

2. If you want to verify that the interface times out, you need to make a breakpoint when requesting the interface to retrieve the interface url, wait until the time-out expires, and then simulate the request in the browser.

3. If you want to verify that the private key is incorrect, you need to set a breakpoint to retrieve the interface url, modify the private key configuration of business, and then simulate the request in the browser.

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.