Designing Authentication for Your Public API Platform
When creating an API platform, one of the key elements is that you need to know your client’s identity and verify their identity to see if it is a valid request from an authorized user.
For API Authentication, basically, we can have two approaches:
Token-based authentication (We won’t discuss this approach in this post)
HMAC authentication
How does it work?
Today, we are going to discuss HMAC authentication. It is commonly used in customer-facing API platforms for identifying user identity.
Client login to your portal and generate an API key and API secret
The client sorts the data (algorithm, apiKey, payload) with provided signing rules and uses the API secret to sign the sorted data by using HMAC. (*The reason for sorting the data is that we want to follow the same rules and sign the data again after receiving)
The client sends the request to the API platform with Algorithm, API Key, Signature, and Payload
The API platform receives the request and extracts the Algorithm, API Key, and Signature from the HTTP header and extracts the Payload from the HTTP body
The API platform uses the same signing rules to sign a new signature
Compare the new signature with the received signature to see if it is the same
Security Brainstorm
Secret Key Leak
This cannot be prevented since we can’t control our clients but we can strengthen the security on our side. We can provide an Automatic Key Rotation to rotate the secret key periodically and also provide a way for our client to disable or regenerate API Key and Secret manually.
Man in the Middle Attack
This can be prevented by the HMAC data signature. Even if the attacker gets the payload and modifies it, the forged data cannot pass our validation if the attacker does not have a correct API Key and Secret.
Replay Attack
This can be mitigated by adding an expiry timestamp on the API and adding to the data signature.