Packages
auth_plug
0.11.0
1.5.2
1.5.1
1.5.0
1.4.21
1.4.20
1.4.19
1.4.18
1.4.17
1.4.16
1.4.15
1.4.14
1.4.13
1.4.12
1.4.11
1.4.10
1.4.9
1.4.8
1.4.7
1.4.6
1.4.5
1.4.4
1.4.3
1.4.2
1.4.1
1.4.0
1.3.7
1.3.6
1.3.5
1.3.4
1.3.3
1.3.2
1.3.1
1.3.0
1.2.3
1.2.2
1.2.1
1.2.0
1.1.1
1.1.0
1.0.0
0.16.0
0.15.0
0.14.0
0.13.0
0.12.0
0.11.0
0.10.0
0.9.0
0.8.0
0.7.0
0.5.0
0.4.0
0.3.1
0.3.0
0.2.1
0.2.0
0.1.4
0.1.3
0.1.2
0.1.1
0.1.0
Turnkey Auth Plug lets you protect any route in an Elixir/Phoenix App.
Current section
Files
Jump to
Current section
Files
lib/token.ex
defmodule AuthPlug.Token do
@moduledoc """
Token module to create and validate jwt.
see https://hexdocs.pm/joken/configuration.html#module-approach
"""
use Joken.Config
@secret System.get_env("SECRET_KEY_BASE")
@doc """
`create_signer/1` creates a signer for the given `secret` key.
It uses the HS256 (HMAC with SHA-256) to generate the signature.
if you're wondering what "HS256" is, read:
community.auth0.com/t/jwt-signing-algorithms-rs256-vs-hs256/7720
"""
def create_signer(secret) do
Joken.Signer.create("HS256", secret)
end
@impl true
def token_config do
# ~ 1 year in seconds
default_claims(default_exp: 31_537_000)
end
@doc """
`generate_jwt!/1` invokes `Joken.generate_and_sign/3`
claims are the data to be signed.
Throws an error if anyting in the claims is invalid.
"""
def generate_jwt!(claims) do
generate_jwt!(claims, @secret)
end
@doc """
`generate_jwt!/2` invokes `Joken.generate_and_sign/3`
`claims` are the data to be signed and `secret` is the secret key.
"""
def generate_jwt!(claims, secret) do
signer = create_signer(secret)
{:ok, token, _claims} =
token_config()
|> Joken.generate_and_sign(claims, signer)
token
end
@doc """
`verify_jwt/1` verifies the given JWT and returns {:ok, claims}
where the claims are the original data that were signed.
"""
def verify_jwt(token) do
verify_jwt(token, @secret)
end
@doc """
`verify_jwt/2` verifies the given JWT and secret.
Returns {:ok, claims} where the claims are the original data that were signed.
"""
def verify_jwt(token, secret) do
signer = create_signer(secret)
token_config()
|> Joken.verify_and_validate(token, signer)
end
@doc """
`verify_jwt!/1` verifies the given JWT and returns claims
where the claims are the original data that were signed.
"""
def verify_jwt!(token) do
verify_jwt!(token, @secret)
end
@doc """
`verify_jwt!/2` verifies the given JWT and returns claims
where the `token` is the JWT that was signed `secret` is the secret key.
Returns `claims` the original claims contained in the JWT.
"""
def verify_jwt!(token, secret) do
signer = create_signer(secret)
{:ok, claims} =
token_config()
|> Joken.verify_and_validate(token, signer)
claims
end
end