Plug.Crypto.verify
verify
, go back to Plug.Crypto module for more information.
Decodes the original data from the token and verifies its integrity.
Examples
In this scenario we will create a token, sign it, then provide it to a client
application. The client will then use this token to authenticate requests for
resources from the server. See Plug.Crypto
summary for more info about
creating tokens.
iex> user_id = 99
iex> secret = "kjoy3o1zeidquwy1398juxzldjlksahdk3"
iex> user_salt = "user salt"
iex> token = Plug.Crypto.sign(secret, user_salt, user_id)
The mechanism for passing the token to the client is typically through a cookie, a JSON response body, or HTTP header. For now, assume the client has received a token it can use to validate requests for protected resources.
When the server receives a request, it can use verify/4
to determine if it
should provide the requested resources to the client:
iex> Plug.Crypto.verify(secret, user_salt, token, max_age: 86400)
{:ok, 99}
In this example, we know the client sent a valid token because verify/4
returned a tuple of type {:ok, user_id}
. The server can now proceed with
the request.
However, if the client had sent an expired or otherwise invalid token
verify/4
would have returned an error instead:
iex> Plug.Crypto.verify(secret, user_salt, expired, max_age: 86400)
{:error, :expired}
iex> Plug.Crypto.verify(secret, user_salt, invalid, max_age: 86400)
{:error, :invalid}
Options
:max_age
- verifies the token only if it has been generated "max age" ago in seconds. Defaults to the max age signed in the token (86400):key_iterations
- option passed toPlug.Crypto.KeyGenerator
when generating the encryption and signing keys. Defaults to 1000:key_length
- option passed toPlug.Crypto.KeyGenerator
when generating the encryption and signing keys. Defaults to 32:key_digest
- option passed toPlug.Crypto.KeyGenerator
when generating the encryption and signing keys. Defaults to:sha256