Which authentication strategy should you use for Rails API?
How to implement a secure authentication strategy is by the far the most confusing part of building an API.
It’s important to evaluate your app requirements before choosing any strategy in the first place to avoid any security implications.
To help you figure out which authentication strategy is the best for your case, here are 5 possible solutions for you:
If your API is running as a standalone app and you don’t need a web interface of any sort, then a header-based token auth might be enough.
If you’re looking for a simple and secure token-based authentication auth strategy, you can use this gem to generate the JWT (JSON Web Token) to send on your Authentication Request Header.
It provides an out of the box JWT token strategy mechanism.
You need to implement the token verification on the server-side. You can use Rails HTTP authentication support for that.
Is a token based authentication solution with token refreshing & allowlisting for APIs built on Rails.
It’s built on top of jwt-ruby, so besides all the JWT functionalities, you also get account creation and authentication features.
It’s a clean and simple solution. It can be used with Devise, if needed.
You might not even need a gem, because most of it is honestly not that hard to implement yourself. It’s an overhead if you don’t need to expire tokens.
Standard Rails app with API
If you need some sort of account management interface for your API, or to implement oauth or omniauth flows, here are some alternatives:
It’s a flexible OAuth 2 provider functionality to your Rails or Grape app.
It provides all oauth flows. Can be used with Devise. Version > supports Rails API-only mode as well.
Don’t use it if you don’t need an oauth2 flow.
Use it if your Rails app already uses Devise and you want to add a token-based auth for your API. You can require endpoints to have an authenticated user or not depending on the needs of your API.
If you’re happy with Devise and already use it on your Rails app, it’s the easiest solution. It also makes it easy to add omniauth provider functionality.
Devise is also well know for bloating your Rails app, so keep this in mind. >= Currently supports Rails version ≥ 4.2.0.
Rodauth-rails is built on top of Rodauth, which is an authentication framework alternative to Devise.
Rodauth supports JWT, including refresh tokens functionality. Supports Rails API-only mode.
If you need social logins or omniauth providers, you’ll need to implement yourself but you can build one yourself using the existing Rodauth API.
API authentication can be super confusing. I hope you got some ideas on how to move forward with choosing the strategy that best suit your API requirements. Taking some time to evalute the best strategy earlier can save you lots of time and work.
If you found this post helpful, sign up to get more content like this in your inbox! :)