Auth with Phoenix and Elixir

Feb 6, 2016

For Stackd 2 we’re using Phoenix to build our API. This is my first time using Phoenix, and I love how you can use plugs and pattern matching to perform authentication and authorization. Here’s a look at how it works…

Authentication

The first thing we want to do is figure out who is making the request. Our API uses OAuth2, so authentication is done by including an OAuth token in the Authorization header. Our RequireToken plug checks the Authorization header for an OAuth token and if successful it will assign(conn, :token, token). If it’s not successful, it will halt the request and respond with an OAuth error.

Authorization

Our API has two different kinds of tokens:

Service tokens – used to access the API on behalf of internal services

User tokens – used to access the API on behalf of a user

With that in mind, let’s take a look at how our GET /users/:user_id/emails endpoint works. We want to make it so service tokens can list any user’s emails, but user tokens can only list their own emails.

First, we include the RequireToken plug. Then we use Elixir pattern matching to accomplish authorization. We have 3 different index/2 methods our request can match on: