Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Authentication and Security

Authorization and Scopes in Phoenix

Decide what each signed-in user may do: Phoenix 1.8 scopes, scoped context functions, ownership checks, role policies, and how to prevent IDOR bugs.

Authentication answers "who are you?". Authorization answers "what are you allowed to do?". They are different problems, and mixing them up causes the most common web security bug: a signed-in user changes a number in the URL and opens someone else's invoice. This is called an insecure direct object reference (IDOR), and in Phoenix the best defence is to make the wrong query impossible to write.

Phoenix 1.8 builds that defence into its generators with scopes. This lesson explains scopes, then adds role-based checks for actions that depend on who you are. Real code is read-only; the stand-ins model the rules in JavaScript so you can try the failure cases.

The IDOR problem

Look at this controller action. It works, and it is wrong:

ELIXIR
def show(conn, %{"id" => id}) do
  invoice = Billing.get_invoice!(id)      # any invoice in the table
  render(conn, :show, invoice: invoice)
end

Any logged-in user can request /invoices/1, /invoices/2, ... and read everybody's data. Hiding the link in the UI is not protection: attackers do not use your UI. The check must be on the server, in the code that fetches the data.

Scopes: carry the caller with you

A scope is a small struct describing who is making the request and, if you want, more context such as the current organization. mix phx.gen.auth generates one:

ELIXIR
defmodule MyApp.Accounts.Scope do
  alias MyApp.Accounts.User

  defstruct user: nil

  def for_user(%User{} = user), do: %__MODULE__{user: user}
  def for_user(nil), do: nil
end

The plug stores it as conn.assigns.current_scope, and the LiveView hook as socket.assigns.current_scope. The convention is that every context function that touches user-owned data takes the scope as its first argument, and uses it in the query:

ELIXIR
defmodule MyApp.Billing do
  import Ecto.Query
  alias MyApp.Accounts.Scope
  alias MyApp.Billing.Invoice

  def list_invoices(%Scope{} = scope) do
    Repo.all(from i in Invoice, where: i.user_id == ^scope.user.id)
  end

  def get_invoice!(%Scope{} = scope, id) do
    Repo.get_by!(Invoice, id: id, user_id: scope.user.id)
  end

  def create_invoice(%Scope{} = scope, attrs) do
    %Invoice{}
    |> Invoice.changeset(attrs, scope)       # sets user_id from the scope
    |> Repo.insert()
  end
end

Now the controller cannot fetch someone else's invoice, because there is no function that does it:

ELIXIR
def show(conn, %{"id" => id}) do
  invoice = Billing.get_invoice!(conn.assigns.current_scope, id)
  render(conn, :show, invoice: invoice)
end

A request for another user's invoice raises Ecto.NoResultsError, which Phoenix renders as a 404. Returning "not found" instead of "forbidden" is deliberate: it does not confirm that the record exists. Notice that the user_id is never taken from request params; it always comes from the scope. A hidden form field with user_id would be an attack vector (this is called mass assignment), so keep it out of cast/3.

When the application has a default scope configured, the Phoenix 1.8 generators (phx.gen.live, phx.gen.html, phx.gen.context) write scoped code like the above for you, including PubSub topics keyed by the owner, so that live updates also go only to the right people.

Node.js Scoped queries stop IDOR (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Role-based checks

Scopes answer "whose data?". Many apps also need "may this kind of user do this action?", such as an admin deleting any comment while normal users delete only their own. Keep those rules in one place, a policy module with a single function, instead of scattering if user.admin checks through templates and controllers:

ELIXIR
defmodule MyApp.Policy do
  alias MyApp.Accounts.Scope
  alias MyApp.Blog.Comment

  def can?(%Scope{user: %{role: :admin}}, _action, _resource), do: true
  def can?(%Scope{user: user}, :delete, %Comment{user_id: user_id}), do: user.id == user_id
  def can?(%Scope{user: user}, :edit, %Comment{user_id: user_id}), do: user.id == user_id
  def can?(_scope, _action, _resource), do: false
end

Then use it at the action, not just in the UI:

ELIXIR
def handle_event("delete_comment", %{"id" => id}, socket) do
  comment = Blog.get_comment!(id)
  scope = socket.assigns.current_scope

  if Policy.can?(scope, :delete, comment) do
    {:ok, _} = Blog.delete_comment(comment)
    {:noreply, stream_delete(socket, :comments, comment)}
  else
    {:noreply, put_flash(socket, :error, "You can't do that.")}
  end
end

Use the same Policy.can?/3 in the template to hide buttons users cannot use, but remember the template is only convenience. The handler is the lock. The last clause, can?(_, _, _), do: false, makes the system deny by default: a new action or resource type is forbidden until you explicitly allow it.

Libraries such as Bodyguard and LetMe formalize the same pattern, but a plain module is enough for many apps.

Node.js A deny-by-default policy (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Protecting routes and LiveViews

Route-level protection comes from the require_authenticated_user plug and on_mount hook from the previous lesson. For admin areas, add a second hook in a separate live_session:

ELIXIR
live_session :admin,
  on_mount: [
    {MyAppWeb.UserAuth, :require_authenticated},
    {MyAppWeb.UserAuth, :require_admin}
  ] do
  live "/admin/users", Admin.UserLive.Index, :index
end

with an on_mount(:require_admin, ...) that halts with a redirect unless scope.user.role == :admin. Because the check runs in on_mount, it applies both on the first request and when a user navigates inside the live session.

Checklist for every feature you build:

  1. Every context function that returns or changes owned data takes a scope and filters by it.
  2. Ids from params are untrusted: look them up through the scope.
  3. Actions beyond "my own data" go through a policy function with a deny-by-default final clause.
  4. The same rule is enforced in controllers, LiveView event handlers and channels, which are separate entrances to your data.
  5. Write tests where user B tries to touch user A's records and expect a 404 or an error (see Testing Controllers and Contexts).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is an IDOR bug?

    Hiding links is not enough; the server must scope every lookup to the caller.
  2. 2. Where should user_id of a new record come from?

    Never trust the client to say who owns a record. Take it from the authenticated scope.
  3. 3. Why return 404 rather than 403 when a record belongs to someone else?

    A 403 confirms the id is valid, which helps attackers enumerate records.
  4. 4. What does a final catch-all clause returning false give a policy module?

    Forgetting a rule then fails safe instead of open.

Summary

  • Authentication identifies the user; authorization decides what they may do.
  • Scopes carry the caller into context functions so queries are always filtered by owner.
  • Never take ownership fields from params; never trust ids from the browser.
  • Put role rules in one policy module and deny by default.
  • Enforce the same rules in controllers, LiveViews and channels, and test the failure cases.

Next: Web Security in Phoenix