Rest api security design guide

Source: Internet
Author: User

Rest api security design guide

The full name of REST is REpresentational State Transfer. Based on the characteristics of traditional Web, it proposes a unified architecture suitable for both client applications and server applications, to a great extent, the website architecture design is unified and simplified.

Currently in three mainstream Web service implementation solutions, the REST mode service is more concise than the complex SOAP and XML-RPC comparison, more and more web services begin to use REST design and implementation. However, it lacks security features. The rest api security design guide is a guide to rest api security design. We recommend that you read the rest api back-end design and website architects.

1. Introduction to REST APIs

The full name of REST is REpresentational State Transfer, which indicates stateless transmission without session. Therefore, each request must carry authentication information. Rest is based on http and stateless. It is only an architectural method, so its security features must be implemented by ourselves and there is no ready-made architecture. We recommend that all requests be sent over https. The core concept of RESTful web services is "resources ". Resources can be represented by Uris. The client uses the methods defined in the HTTP protocol to send requests to these URIs. Of course, these accessed "Resources" may change their status. The HTTP request correspondence is as follows:

========================================================== =================== HTTP Method behavior example ================================ ==================================================== GET information http://xx.com/api/ordersGET for the resource get information http://xx.com/api/orders/123POST for a particular resource create new resource http://xx.com/api/ordersPUT update resource http://xx.com/api/orders/123DELETE Delete resource http://xx.com/api/orders/123========== ============================== ================================

The request data is generally expressed in json or xml format. json is recommended.

2. Identity Authentication

Identity Authentication includes HTTP Basic, HTTP Digest, api key, Oauth, and JWK:

2.1 HTTP Basic

REST is stateless transmission, so each request must carry the identity authentication information. There are many identity authentication methods. The first method is http basic, this method is simple on the client and simple on the server. You only need to configure apache and other web servers, so it is quite convenient for simple services. However, this method is less secure, that is, simply put the username and password base64 encoding into the header.

Base64 encoding: Basic admin: adminbase64 encoding: Basic YWRtaW46YWRtaW4 = put in the Header: Authorization: Basic YWRtaW46YWRtaW4 =

Because it is a simple base64 encoded storage, remember to pay attention to the use of ssl in this way, otherwise it will be streaking. Some products are also based on this similar method. They do not use the basic mechanism of apache, but write their own authentication framework. The principle is the same. In a request, base64 decodes the Authorization field, verify the authentication information. Obviously there is a problem with this method. authentication information is equivalent to plain text transmission, and there is no brute force cracking protection function.

2.2 API KEY

The API Key is the user identity authentication after the service end to the client to allocate an API Key, similar to: http://example.com/api? Key = dfkaj134. The general process is as follows:

A simple design example is as follows.

Client:

 

Server:

 

The client registers with the server. The server sends the response api_key and security_key to the client. do not disclose the information when saving the file. Then, the client obtains a hash value sign based on the api_key, secrity_key, timestamps, and rest_uri algorithms, the url in the construction process is sent to the server. After receiving the request, the server first verifies whether api_key exists and obtains the security_key of the api_key if it exists. Then, it verifies whether the timestamps exceed the time limit, which can be determined by the system, in this way, some replay attacks are prevented. The rest_api on the way obtains/rest/v1/interface/eth0 from the url, and finally calculates the sign value, verify the signature value with the sign value in the url. This design prevents data tampering. Using this API Key design method, a timestamp is added to prevent partial replay, verification is added, data tampering is prevented, and user names and passwords are transmitted, of course, there will also be some overhead.

2.3 auth1.0a or oau22.

The OAuth Protocol is applicable to authorizing external applications to access resources on this site. The encryption mechanism is more secure than HTTP Digest identity authentication. The usage and configuration are both complex and will not be involved here.

2.4 JWT

JWT is a JSON Web Token used to send things that can pass digital signatures and authentication. It contains a compact, URL-safe JSON object, the server can resolve this value to verify whether it has operation permissions, validity, and other security checks. Due to its compact nature, it can be placed in the url or HTTP Authorization header. The specific algorithm is as follows:

3. Authorization

After identity authentication, authorization is performed. Different access permissions are granted based on different identities. For example, admin users, common users, and auditor users all have different identities. Simple Example:

 

This is the processing of vertical permissions. If A parallel permission problem occurs, such as user A Obtaining user B's identity information or changing other user information, sensitive data interfaces must be judged by users. This step is generally implemented in specific logic implementation.

4. URL filtering

Before entering the logic processing, add URL parameter filtering, such:

/site/{num}/policy

Specify the num position as an integer. If it is not a parameter, an invalid parameter is returned. Set a url list and reject requests that are not included in the url list. This prevents api leakage during development. Rest api interfaces generally use GET, POST, PUT, and DELETE. unimplemented methods do not allow direct return of methods. For POST and PUT methods, the data is in json format, verify json before entering the logic. Invalid json format error is returned.

5. encrypted transmission of important functions

In the first step, we recommend SSL encrypted transmission, and Encrypt transmission of important functions in the system, such as certificates, some data, and configuration backup functions. At the same time, we must ensure that we have the relevant permissions, this step will be involved in authorization.

6. Speed Limit

Request rate limit: you can determine the number of requests for a certain period of time based on api_key or user, and update the data to the memory database (redis, memcached ), when the maximum number is reached, the user's request is not accepted, and the memory database key can be used to automatically expire at a specific time. APC can be used in php. Alternative PHP Cache (APC) is an open and free PHP opcode Cache. It aims to provide a free, open, and sound framework for caching and optimizing PHP intermediate code. Set X-Rate-Limit-Reset when returning: the number of seconds remaining in the current time period. The sample code of APC is as follows:

 

7. handle errors

All requests that are illegal and cause system errors are recorded, and some important operations, such as logon and registration, are displayed through the log interface output. There is a unified error interface. for errors in the 400 series and 500 series, there are corresponding error codes and related message prompts, such as 401: unauthorized; 403: authenticated, however, you do not have the required permissions. If you do not recognize a url:

{"result":"Invalid URL!"}

· Incorrect Request Parameters

{"result":"json format error"}

· METHODS not allowed:

{"result":"Method Not Allowed"}

· Invalid parameters. All of the above are single status codes, and there are multiple status codes, indicating that part of the code is successful and some characters are invalid. Example:

 

8. Important ID opacity Processing

Some sensitive functions of the system, such as/user/1123, can obtain information of users with id = 1123. To prevent dictionary traversal attacks, you can perform url62 or uuid processing on the id, the id to be processed in this way is unique and character-safe.

9. Other Precautions

(1) Request data. For POST and DELETE methods, the data adopts json format. Of course, it does not mean that the rest architecture does not support xml. Because xml is too bad to parse, json is sufficient for most applications, recently, json is becoming more and more popular, and the json format does not have xml security problems, such as xxe. Currently, the scanner can automatically scan data in json format.

(2) returned data unified encoding format, unified return Type, such as Content-Type: application/json; charset = "UTF-8 ″

(3) In logic implementation, parameter verification or escape operations are performed after json decoding. The first step is json format verification, and the second step is specific parameter verification, which can basically prevent most injection problems.

(4) SSL is used during transmission to ensure transmission security.

(5) secure storage, encrypted storage of important information, such as hash Storage of authentication information.

In short, try to use SSL.

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.