Plug support for HMAC authentication. This is used for authentication between server sides.
This package can be installed by adding plug_hmac_auth
to your list of dependencies in mix.exs
:
def deps do
[
{:plug_hmac_auth, "~> 0.1.0"}
]
end
Here we demonstrate the usage by this example. Replace the PlugHmacAuthExample
by the name of your own web site.
We use some raw data as payload to verify the request from client.
For those GET
requests, we use query string
as payload.
For other requests, we use raw body
as payload. But the raw body of request can only be read once. That means we can't read the raw body after the Plug.Parsers
. Instead of the original body reader provided by Plug.Parsers
, we need to use a custom body reader to cache the raw body
.
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library(),
body_reader: {PlugHmacAuth.BodyReader, :read_body, []}
In the router module of your web site, define a new pipeline to enable the plug of HMAC authentication:
pipeline :plug_hmac_auth do
plug(PlugHmacAuth,
key_access_id: "x-access-id",
key_signature: "x-access-signature",
hmac_hash_algo: :sha512,
secret_handler: PlugHmacAuthExample.Handlers.SecretHandler,
error_handler: PlugHmacAuthExampleWeb.ErrorHandler
)
end
Module PlugHmacAuth
needs these options:
key_access_id
: The key ofaccess_id
in the HTTP request header.key_signature
: The key ofsignature
in the HTTP request header.hmac_hash_algo
: The algorithm of HMAC.secret_handler
: Secret handler is the module to get thesecret
by givenaccess_id
.error_handler
: Error handler is the module to handle the unauthorized request.
Here lists the algorithms current supported.
We need to implement the callback function of get_secret_key/1
to let authenticator know how to get the secret key by given access id.
We need to implement the callback function of auth_error/2
to let the authenticator know how to handle the unauthorized request.
See HexDocs.