Handle authorization failures with action_fallback
mainThe recommended way to handle authorization failures in Phoenix controllers is using the action_fallback/1 macro. This allows a dedicated controller to handle {:error, reason} results returned by your actions.
To prevent leaking the existence of resources, you can return {:error, :not_found} from your policy instead of the default :unauthorized, and handle that specific error in your fallback controller to render a 404.
# lib/my_app_web/controllers/fallback_controller.ex
module MyAppWeb.FallbackController do
use MyAppWeb, :controller
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(:forbidden)
|> put_view(html: MyAppWeb.ErrorHTML)
|> render(:"403")
end
end
# lib/my_app_web/page_controller.ex
module MyAppWeb.PageController do
use MyAppWeb, :controller
action_fallback MyAppWeb.FallbackController
# ...actions here...
end