For API auth - phx.gen.auth or Pow?

I’m trying to implement auth for a Phoenix Json API with a React frontend - phx.gen.auth seems to provide alot for a Phoenix only (/ with Liveview) app whereas the Pow library explicitly instructs on using it for a Json API. Should I give up on trying to retrofit phx.gen.auth to work for this case & just use Pow? Does someone have an example of using phx.gen.auth for Json APIs?

2 Likes

API protection with tokens can be very easily implemented with Phoenix tokens, therefore no external dependencies needed.

Phoenix Token:

Tokens provide a way to generate and verify bearer tokens for use in Channels or API authentication.

Using a Phoenix Token per user:

How To’s:

I am not saying that this the way you should go, but it’s na alternative you may want to consider due to it’s simplicity and no need of further dependencies.

5 Likes

You can easily extend phx.gen.auth for this.
If you look at the generated code for the session token, it’s just some random bytes stored in the database. Just change the context to e.g “api” and you have your API tokens.
Then just add a plug checking the token for incoming requests and you are done.

The advantage of storing the tokens in your db, is that you can revoke them easily (you can also do this with Phoenix.Token).

2 Likes

I don’t think you make a mistake with either. If you will require social logins later might be easier to do it with Pow. On the other hand Pow doesn’t have a builtin LiveView story.

1 Like

Hello @zzyyxx were you able to find the right way to do this I’m looking for a better way to do authentication in Phoenix for REST APIs

1 Like