Skip to content

Blogging On Rails

Everything on Rails!

How do you get Devise working with your Rails API?

Let’s say you’re building an app on iOS, and you’ve already built an API and you’ve chosen Devise, but you’re stuck because you cannot authorize your user like you can in your web browser. What do you do?

One area where where Devise seems to be lacking support is API authentication, especially with HTTP requests from an iOS app. The reason for this is the lack of browser cookies. Devise uses Rails’ secure cookie to store data about your logged in user between each request. Your iOS app doesn’t have that cookie session, so you will need to do some extra work.

In your app, you could store a user’s credentials and, since you’re using SSL, send the credentials with each API request. On the Rails side, you would pull out the credentials, perhaps from the HTTP headers, and then manually authenticate the user with Devise’s sign in methods.

Building on this technique, you could generate a string token of some sort, perhaps using Ruby’s SecureRandom library in the API after authenticating a user for the first time. The API would return that token back to the client and then on every subsequent API request, your API would look up the user with the token and make sure that the user exists. Logging out a user becomes setting the token to nil. You can also speed up the database lookup by adding an index to that token field.

Now you’re able to use Devise to handle a lot of the authentication boiler plate, and you’re able to spend your time building your iOS app and API without wasting a day figuring out how to get your user authenticated on the client.

Looking to make your Rails app more interactive?

Subscribe below, and you won’t miss the next Rails tutorial, that will teach you how to make really interactive web apps that just work.

We won’t send you spam. Unsubscribe at any time.

Leave a Reply

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