access_token v1.0.1 AccessToken View Source
Access token generation and processing.
First off, the secret signing key must be configured in the application environment,
usually defined in config/config.exs
:
config :access_token, key: "6m/pr714TP8ijQeVdJ2gBOxuYwrD7nR/p5BhhcQ2ejURZpNYz9T//ze9mfx+TNpo"
AccessToken
provides a simple interface to generate and process access tokens:
iex> access_token = AccessToken.encode(%{user_id: 1})
iex> AccessToken.decode(access_token)
{:ok, %{user_id: user_id}}
Link to this section Summary
Functions
Returns a tuple {:ok, info}
with the information encoded in the access token, or
{:error, :invalid}
otherwise
Returns an access token, a string representing the information provided that is encoded in a JSON Web Token (JWT)
Link to this section Functions
decode(String.t) :: {:ok, any} | {:error, :invalid} | {:error, :expired}
Returns a tuple {:ok, info}
with the information encoded in the access token, or
{:error, :invalid}
otherwise.
iex> access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJfV"
iex> AccessToken.decode(access_token)
{:ok, %{user_id: 1}}
Temporary access tokens might return the tuple {:error, :expired}
if the expiration time
passed.
Caveats
In the process of decoding, all the Map
keys are converted to atoms.
iex> AccessToken.encode(%{"user_id" => 1}) |> AccessToken.decode()
{:ok, %{user_id: 1}}
encode(any, DateTime.t | integer) :: String.t
Returns an access token, a string representing the information provided that is encoded in a JSON Web Token (JWT).
iex> AccessToken.encode(%{user_id: 1})
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJfV"
Every access token is unique, no matter what information it carries.
All access tokens are permanent by default. Temporary access tokens can be created by
passing the expiration time (a DateTime
or a UNIX timestamp in seconds) on or after
which the access token MUST NOT be accepted for processing.
iex> expiration_time = DateTime.to_unix(DateTime.utc_now()) + 3600
iex> AccessToken.encode(%{user_id: 1}, expiration_time)
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJObG83bnJObU44cjdfSEk2Q2x6NFRNcmFq"