View Source Authex.Plug.Authentication (Authex v2.3.0)
A plug to handle authentication.
This plug must be passed an auth module in which to authenticate with. Otherwise,
it will raise an Authex.Error.
With it, we can easily authenticate a Phoenix controller:
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
plug Authex.Plug.Authentication, with: MyApp.Auth
def show(conn, _params) do
with {:ok, %{id: id}} <- MyApp.Auth.current_user(conn),
{:ok, user} <- MyApp.Users.get(id)
do
render(conn, "show.json", user: user)
end
end
endThe plug looks for the Authorization: Bearer mytoken header by default. It
will then verify and covert out token into a resource using the provided auth
module. You can optionally set a :param value to enable tokens from query
parameters.
We can then access our current resource from the conn using Authex.current_resource/1.
By default, if authentication fails, the plug sends the conn to the Authex.Plug.Unauthorized
plug. This plug will put a 401 status into the conn with the body "Unauthorized".
We can configure our own unauthorized plug by passing it as an option to this plug.
options
Options
:with- The auth module that will be used for verification and token conversion.:unauthorized- The plug to call when the token is invalid - defaults toAuthex.Plug.Unauthorized.:header- The header to extract the token from - defaults to"authorization".:param- A query parameter to extract tokens from - defaults tonil(no use of params).
Link to this section Summary
Link to this section Types
@type options() :: [option()]