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, on_verifying: &verify_function/1
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
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, config_module: MyJWTConfig
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
end
Options
This plug accepts the following options in its initialization:
on_verifying
: a function used to verify the token. Receives a Token and must return a Tokenon_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_on_verifying
: Same ason_verifying
above. Overrideson_verifying
if it was defined on the Plugjoken_on_error
: Same ason_error
above. Overrideson_error
if it was defined on the Plug