Packages
joken
0.13.0
2.6.2
2.6.1
2.6.0
2.5.0
2.4.1
2.4.0
2.3.0
2.2.0
2.1.0
2.0.1
2.0.0
2.0.0-rc3
2.0.0-rc2
2.0.0-rc1
2.0.0-rc0
1.5.0
1.4.1
1.4.0
1.3.2
1.3.1
1.3.0
1.2.2
1.2.1
1.2.0
1.1.1
1.1.0
1.0.1
1.0.0
0.16.1
0.16.0
0.15.0
0.14.1
0.14.0
0.13.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.8.1
0.8.0
0.7.0
0.6.2
0.6.1
0.6.0
0.5.0
0.1.0
JWT (JSON Web Token) library for Elixir.
Current section
Files
Jump to
Current section
Files
lib/joken.ex
defmodule Joken do
alias Joken.Token
alias Joken.Utils
@type algorithm :: :HS256 | :HS384 | :HS512
@type status :: :ok | :error
@type payload :: map | Keyword.t
@moduledoc """
Encodes and decodes JSON Web Tokens.
Usage:
Looks for a joken config block with `secret_key`, `algorithm`, and `json_module`. Json module being a module that implements the `Joken.Codec` Behaviour
defmodule My.Json.Module do
alias Poison, as: JSON
@behaviour Joken.Json
def encode(map) do
JSON.encode!(map)
end
def decode(binary) do
JSON.decode!(binary, keys: :atoms!)
end
end
config :joken
secret_key: "test",
json_module: My.Json.Module,
algorithm: :HS256, #Optional. defaults to :HS256
then to encode and decode
{:ok, token} = Joken.encode(%{username: "johndoe"})
{:ok, decoded_payload} = Joken.decode(jwt)
"""
@doc """
Encodes the given payload and optional claims into a JSON Web Token
Joken.encode(%{ name: "John Doe" }, %{ iss: "self"})
"""
@spec encode(payload, payload) :: { status, String.t }
def encode(payload, claims \\ %{}) do
json_module = Application.get_env(:joken, :json_module)
algorithm = Application.get_env(:joken, :algorithm, :HS256)
Token.encode(secret_key, json_module, payload, algorithm, claims)
end
@doc """
Decodes the given JSON Web Token and gets the payload. Optionally checks against
the given claims for validity
Joken.decode(token, %{ aud: "self" })
"""
@spec decode(String.t, payload) :: { status, map | String.t }
def decode(jwt, claims \\ %{}) do
json_module = Application.get_env(:joken, :json_module)
algorithm = Application.get_env(:joken, :algorithm, :HS256)
Token.decode(secret_key, json_module, jwt, algorithm, claims)
end
defp secret_key do
secret_key = Application.get_env(:joken, :secret_key)
if Application.get_env(:joken, :decode_secret_key?, false) do
Utils.base64url_decode(secret_key)
else
secret_key
end
end
end