Can phx.gen.auth be used for API authentication?

Just curious if the basic auth framework generated by phx.gen.auth can be ‘easily’ converted to work with a JSON api.

Can you expand on what you mean by “work with a JSON API”? I can think of two scenarios that meet that description and they have different answers for your question.

If you mean “connected to a JS frontend via JSON-formatted requests”, the conversion wouldn’t need to change that much. The biggest change might be with the details of where authentication data is in the request; best-practice with JSON APIs would be a bearer token, versus the cookie-based session used by default.

If you mean “as an authentication system for a JSON API called by other programs” (either via HTTP Basic or API key), the generated code would be a lot less useful.

Ah yeah sorry I can see how that would be confusing. I mean the former - connected to a JS frontend. I’ve read in a few different places how JWT’s are apparently subjectively worse than sessions. Thoughts on that? Why wouldn’t the cookie-based session be good practice?

JWT is a token that allows you to maintain user sessions. So what do you mean that they are worse than sessions?

Cookie is designed to work without the JS frontend. By default, cookie session in phoneix is http only (not accessible by the js) and unencrypted (but signed so is tamper-proof). If you log in via conventional http that it is fine; if you want to have fancy login in javascript driven frontend, then it is not as easy to work with.

A bearer token is an opaque token, whereas a JWT token in the cookie session contains trusted data. With a bearer token you keep all session data server side in a ETS table or something, so it is safer and easier to work with in js.


Could you elaborate on this please? I think whether we work with cookies or not it doesn’t matter? As long as the server has an appropriate success/failure response for its login service? I guess you see something I don’t see:)

phx.gen.auth stores it in DB. Storing the sessions in ETS wouldn’t allow having long lasting sessions (e.g. 60 days default for phx.gen.auth when remember-me is checked) without a huge cost in memory? Anyway it might be an option indeed but interesting that you mentioned that one as an example instead of some relational DB.

Without a concrete design I cannot comment anymore. You probably have some requirements that we don’t know, so no one else can design it for you. If you have a plan, but want a second opinion, then please post your plan first.