Separate API Authentication & Authorisation Pipelines

I have a brand new Absinthe powered API in the works.

Just wondering about people’s approach to authentication.

I am happy with the authorization part, following the Absinthe tutorial -> a Phoenix.Token being passed in a header and then verified (JWT is prob overkill for me).

I reckon I have to break out initial authentication from the GraphQL pipeline which includes the header check - and put authentication into its own pipeline.

This makes sense to me, but I would like if anyone else wants to share their experience or best practices.

I’ve been building an absinthe powered API as well and am also writing a blog post about it.

This is the general setup I’m using, https://github.com/hl/socka and below are some snippets of how I’m building it at a much larger project.

This is how I’m solving authentication:

Router
Use LoadResource to load a User or SalesChannel for Absinthe to use
https://gist.github.com/hl/5805bab28849b272d9f7c5a9faa2d6e3

LoadResource
Look at a random generated token and load the corresponding resource
https://gist.github.com/hl/b9b310e2109901dbbd5ed0ffd68d27f9

UserMiddleware
Check if a user is set in the absinthe context, otherwise create an error result
https://gist.github.com/hl/3f395e888c2e0e05bc2af5ccfeaacaf8

ProductType
Make sure the middleware is run before the resolvers
https://gist.github.com/hl/53e4a4663356ff1d3012fffb4eda37fe

ErrorMiddleware
Handle all errors
https://gist.github.com/hl/75d48e544e43951a5de88776383b99a6

And as far as authorization goes:

Helpers
Helper macro
https://gist.github.com/hl/f0feaad5c826f77b9a4fda342d8aa0a4

Permissions
Protocol
https://gist.github.com/hl/733c2ef950c28828bde72891cc541169

ProductResolver
Get the user from the context and use it with the macro check_permissions
https://gist.github.com/hl/5114b4400d5a914b601bce9097b667ee

Authorizer
Protocol
https://gist.github.com/hl/a9e1794a102927fa38c536444a24cf3f

ProductAuthorizer
https://gist.github.com/hl/7682f31cc6e9b755070dfe09001be5f6

3 Likes

Looking at this post I realise that some parts could be optimized a bit better :smiley: