Protecting the API

Hello,

I am creating my first Ash Json API with Phoenix.

I am playing with swagger, and I have some questions.

  1. How can I add authentication and authorization? Is it derived from AshAuthentication policies?
  2. How can I get the bearer to test the API authorization?

If I define a policy like this one:

  policies do
    policy always() do
      forbid_if always()
    end
  end

Note I am using this policy only for testing purposes

  1. In the GET action for listing all the items without any API key, it returns a 200 response with an empty list. Shouldn’t be a 401 instead?

I want to return 401 to all API calls that are not authorized using a bearer, and a 403 response to HTTP calls not allowed—for example, a resource owned by another actor.

Thanks!

If you want to forbid anyone without a bearer token that is best done in a plug in your router.

Are you using AshAuthentication?

Read actions apply policies by filtering by default. This protects from various security problems.You can change that by setting access_type :strict in the policy, but I suggest sticking with the default.

If you want to enforce in each resource or domain (policies can also go on the domain) you can add a policy like this:

policies do
  policy actor_absent() do
    access_type :strict
    forbid_if always()
  end

  ...rest of policies
end
2 Likes

Thanks @zachdaniel !

1 Like