Joken v1.2.0 Joken.Plug
A Plug for signing and verifying authentication tokens.
Usage
There are two possible scenarios:
- Same configuration for all routes
- Per route configuration
In the first scenario just add this plug before the dispatch plug.
defmodule MyRouter do
use Plug.Router
plug Joken.Plug, verify: &MyRouter.verify_function/0
plug :match
plug :dispatch
post "/user" do
# will only execute here if token is present and valid
end
match _ do
# will only execute here if token is present and valid
end
def verify_function() do
%Joken.Token{}
|> Joken.with_signer(hs256("secret"))
|> Joken.with_sub(1234567890)
end
end
In the second scenario, you will need at least plug ~> 0.14 in your deps. Then you must plug this AFTER :match and BEFORE :dispatch.
defmodule MyRouter do
use Plug.Router
# route options
@skip_token_verification %{joken_skip: true}
plug :match
plug Joken.Plug, verify: &MyRouter.verify_function/0
plug :dispatch
post "/user" do
# will only execute here if token is present and valid
end
# see options section below
match _, private: @skip_token_verification do
# will NOT try to validate a token
end
def verify_function() do
%Joken.Token{}
|> Joken.with_signer(hs256("secret"))
|> Joken.with_sub(1234567890)
end
end
Options
This plug accepts the following options in its initialization:
verify
(required): a function used to verify the token. The function must at least specify algorithm used and your secret using thewith_signer
function (see above). Must return a Token.on_error
(optional): a function that will be called withconn
andmessage
. Must return a tuple containing the conn and a binary representing the 401 response. If it’s a map, it will be turned into json, otherwise, it will be returned as is.
When using this with per route options you must pass a private map of options to the route. The keys that Joken will look for in that map are:
joken_skip
: skips token validationjoken_verify
: Same asverify
above. Overridesverify
if it was defined on the Plugjoken_on_error
: Same ason_error
above. Overrideson_error
if it was defined on the Plug