Authex.Plug.Authorization (Authex v2.2.0) View Source
A plug to handle authorization.
The plug must also only be used after the Authex.Plug.Authentication
has been used.
With it, we can easily authorize a Phoenix controller:
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
plug Authex.Plug.Authentication, with: MyApp.Auth
plug Authex.Plug.Authorization, permits: ["user", "admin"]
def show(conn, _params) do
with {:ok, %{id: id}} <- Authex.current_resource(conn),
{:ok, user} <- MyApp.Users.get(id)
do
render(conn, "show.json", user: user)
end
end
end
The plug checks the scopes of the token and compares them to the :permits
passed
to the plug. Authorization works by combining the "permits" with the "type" of
request that is being made.
For example, with our controller above, we are permitting "user" and "admin" access.
The show action would be a GET
request, and would therefore be a "read" type.
Requests are bucketed under the following types:
- GET - read
- HEAD - read
- PUT - write
- PATCH - write
- POST - write
- DELETE - delete
So, in order to access the show action, our token would require one of the
following scopes: ["user/read", "admin/read"]
. Or, the token would require
["user/write", "admin/write"]
to access the update action.
By default, if authorization fails, the plug sends the conn to the Authex.Plug.Forbidden
plug. This plug will put a 403
status into the conn with the body "Forbidden"
.
We can configure our own forbidden plug by passing it as an option to this plug.
Options
:forbidden
- The plug to call when the scopes are invalid - defaults toAuthex.Plug.Forbidden
.:permits
- A list of permits that the token scopes must have at least one of.
Link to this section Summary
Link to this section Types
Specs
Specs
options() :: [option()]