Rails 8 - adding API token support

Hi,

me again. As a disclaimer, I am a data scientist in need of a database/api/gui solution and landed on rails. I have used ruby a lot in the past so it seemed like a sensible option. That said, many questions remain that probably seem trivial to web developers :wink:

Including this one:

I have today switched my project from rails 7 to 8 (early stages, so that just took 10mins). One reason was the built-in authentication generator - which works fine, if you know how to google for a way to actually sign up users (weird omission, honestly…).

The whole authentication business (controller, model) seems to be exclusively geared towards “Html”, using cookies and whatnot. Which is fine, but I also need a way to authenticate via the REST API since I will be loading a bunch of data into the system via rest calls. I understand that this would involve authentication via rest using username/password, getting back a token which is then included in the actual data loading calls. Which in turn means I need to be able to generate a token upon authentication, return it to the user when authenticating via REST, have the token expire and all that while still keeping cookie support (?) for users authenticating via the front end?

Which leaves the question… how would that all work on the controller/model level?

A high-level answer is fine, or even better a link to a blog or similar that shows an example of how to do it. Most resources I could find rely on rails <= 7 and various gems.

The closest practical example I could find was this: Build an API in Rails with Authentication

But the author unfortunately rips out all the “html” side of things and gears it to API access only. So if there is a short answer as to how to use that particular implementation in both worlds, that would also be helpful.

/M

Just to confirm - further digging suggests that this is perhaps best done by building a completely stand-alone API within the App using something like grape.

Does that sound reasonable?

I’d say “yes”

Reading from thia headline in the post

Build an API in Rails with Authentication

You see the whole api being in its own namespace - and only be responsible for api with json. No html, that’s up to controllers in a different namespace :ok_hand:

hey! I found your topic through the “Related topics” of my topic, so feature works well. I just proposed adding a token option to the new Rails 8 authentication generator, so feel free to support my proposal : Proposal: Authentication via JWT token

cheers