RESTful API is a protocal based on HTTP. Sometimes we want to encrypt the RESTful API content while using. There are three encryption in practise:
1. HTTP Basic Authentication
HTTP supported a simple and basic authentication natively, namely put an extra field named Authorization: Basic em1rOjEyMzQ1Ng==
in the header. i.e. We can let our clients login with username and password. Here, em1rOjEyMzQ1Ng==
is encrypted by Base64
. In practise, we DON’T recommend to use this way, as Base64
is very easy to decrypt.
2. Access Token
When clients login with correct username and password, server will generate an Access Token
and assign an Expiry Date
on it. Every time, when a request is made by client, Access Token
must be attached to it, and will be verified by server. When client logs out, server will destroy this Access Token
.
The benefits of this approach is easy to implement for current resources, but the drawback is obvious too. Access Token
can be captured using tools such as WiredShark
. If the server set the Expiry Date
too long, clients may get all the resources any time they want.
3. API Key + Security Key + Sign
This way is commonly and widely used and can be divided into few steps:
- Step 1: User login successfully and server returns with
api_key
andsecurity_key
; - Step 2: On the user’s (client) side,
security_key
,api_key
,api_endpoint
,timestamp
, andrequest_parameters
are used to create asign
- Step 3: Whenever user want to make a new request,
sign
,api_key
,api_endpoint
,timestamp
andrequest_parameters
are sent to server - Step 4: Server takes above 5 fields, validate the
timestamp
and check thesign
based onapi_key
andsecurity_key
.
One of the practicial example is JWT:
Compared with HTTP Basic Authentication
and Access Token
, API Key + Security Key + Sign
is the most frequently used for creating RESTful with Authentication. One Example using such a (similar) protocol is JWT
https://jwt.io/. The workflow is (from its own website):
In above picture, the JWT
is just a string consisted of header, payload and signature.
- Header: Describe the basic informaton about the JWT, such as the encrpytion algorithm.
{
"typ": "JWT",
"alg": "HS256"
}
The above example shows this jwt is using HS256
.
- Payload:
One example of payload:
{
"iss": "JWT issuer", // JWT issuer
"iat": 1441593502, // issued at what time
"exp": 1441594722, // JWT expiration date and time
"aud": "www.example.com", // Audience claim, this JWT intended for which users
"sub": "[email protected]" // Subject claim
}
- Signature: JWT is using base64 to encode payload and header and put them together and encrpyt with a secret provided by user in the following format:
base64-encoded header.base64-encoded payload.base64-encoded signature
Reference
https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32