I’ve covered a few authentication plugins in the past. I guess it is time to write something for another free plugin. This time I will cover the usage of HMAC authentication plugin.
Documentation of this plugin is pretty good, the purpose of this post is to give you a working example out of box so you can try yourself.
Usage example
As usual, I will use Admin API to set up this plugin in the first part.
This is the most important part of using this plugin. Depends on what users set for config.enforce_headers, some of the headers must be used to generate HMAC signature. Each entry MUST be on a new line.
For example, let’s say we want to send curl -X GET http://localhost:8000/test/anything and we have set config.enforce_headers=date request-url host.
Let’s use curl to check the request headers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
curl -vs http://localhost:8000/test/anything > /dev/null * Trying ::1:8000... * Connected to localhost (::1) port 8000 (#0) > GET /test/anything HTTP/1.1 > Host: localhost:8000 > User-Agent: curl/7.77.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 401 Unauthorized < Date: Thu, 08 Jul 2021 06:22:05 GMT < Content-Type: application/json; charset=utf-8 < Connection: keep-alive < Content-Length: 30 < X-Kong-Response-Latency: 2 < Server: kong/2.4.1.1-enterprise-edition < { [30 bytes data] * Connection #0 to host localhost left intact
As we can see here GET /test/anything HTTP/1.1 is the request-url, Host: localhost:8000 is host. The date header needs to be used when we send the request. Let’s say it is the same as the response time Date: Thu, 08 Jul 2021 06:22:05 GMT.
The signature string for calculating our HMAC signature is below.
Now that we have the signature string, you can calculate HMAC signature.
If you set config.validate_request_body=true, you need to calculate request body’s sha256 digest and put a digest header in your request. You need to also include this digest header in your signature string.
I will provide a shell script at the end of this article. You can use it for calculating HMAC signature.
Make API call with Authorization header
Let’s say the signature we got is QiMr2Oq4nm55NAFSiGUnhgnDFTGFHQpS6Qvb2KIprak=, we can make api call again as below:
#! /bin/sh printf "Enter your user_name and press [ENTER]: \n" read username printf "Enter your secret and press [ENTER]: \n" read token printf "Enter your host_name (e.g.: example.com:8000) and press [ENTER]: \n" read hostname printf "Enter your request line (e.g.: GET /test HTTP/1.1) and press [ENTER]: \n" read request printf "Enter your request body and press [ENTER]: \n" read request_body
TS=$(date -u "+%a, %d %b %Y %T GMT")
echo "\nHeaders to include in your request:\n" echo "Date: $TS"