Rails, Devise and APIs

As a newcomer to Rails and having done a fair amount of background reading, it seemed to make sense that I use Devise to secure access to the API that I was creating. However, in the end I gave up, I could not get the authentication to work reliably and I could not stop Devise from sending HTML out in response to a JSON request. I know that better men than I would have fixed the problem but, as I dug into the issues, I got the feeling that I was going to spend more time removing functionality than I would spend writing what I needed from scratch.

Devise does a lot but, to my mind, a lightweight API doesn’t need much. However, there isn’t much out there to tell you what you need to do. While I was digging around, I came across APIs on Rails which gave me the confidence to remove Devise and start again. I started to work through the examples in the book and had problems with a few of them but there is a Github repository where the issues are discussed and solutions posted. It was not the simplest of processes but it was much more transparent than using Devise.

When it came to Chapter 5, entitled “Authenticating Users” I opted to use Json Web Tokens (JWTs) because they can carry information in much the same manner as a cookie which would, I believed, simplify the implementation server-side. Support for JWTs was added to the project via a Ruby Gem which proved to be well documented and easy to use.

In simple terms the approach is this:

  1. When a client starts a session on the server, they provide their credentials and, in return, are provided a JWT which contains information to identify the client.
  2. The client includes the JWT in the authorization header of every HTTP request sent to the server.
  3. The server opens the JWT, checks the content and allows the request to proceed if everything checks out. If it doesn’t check out, an unauthorised (401) error is returned immediately.

Much simpler than struggling with Devise! Once I got my head around it, it was easy enough to implement. If you are interested, you can take a look at the code on Github.

Rails and Devise are very powerful but so much happens under the hood that they are a minefield for new users who are trying to do something a little out of the ordinary.


Leave a Reply

Your email address will not be published. Required fields are marked *