Use the Simplest Authentication System

Learn about authentication and in what capacity we should implement it in our Rails application.

We'll cover the following

Many developers, upon hearing “API” and “authentication,” will jump to JSON Web Tokens, JWT, or OAuth. Be careful here. If our API is simply a JSON endpoint for consumption by our front end, we can transparently use the existing cookie-based authentication we already have. Remember, the more authentication mechanisms we support, the more vulnerable our app is to security issues because each mechanism is an attack vector.

If our API is being consumed internally, there are two other mechanisms we should consider before adopting something complex like JWT or OAuth, especially if our API does not require a sophisticated set of authorizations. The first is HTTP Basic Auth, which is a name and a password.

Rails provides a http_basic_authenticate_with method that we can call in our controllers to use basic buth. Every HTTP client in the known universe supports basic auth, and we can embed our credentials in a URL for easy debugging and local development like so:

https://username:password@api.example.com/api/widgets.json

For example, in our ApiController base, we could do something like this:

Get hands-on with 1200+ tech skills courses.