This solution redirects the user from our front-end application (AngularJS) to the back-end application (Rails) with a login form (Devise). The user is then redirected back to the front-end application with an Access Token that we'll attach to every request (Grape) in order to authenticate the user (Doorkeeper). This is our happy path:

Demo

We've prepared a sample demo application with meaningful commits, so you can run it and play with it:

We also know that we'll always be dealing with a trusted application and we don't need our users to accept it the first time they log in, so we set it to skip authorization unconditionally. Of course, this might not be the case for you.

Take a note of Application Id. We will need to pass it to our front-end. At Monterail, we do this by injecting JsEnv concern - this concept was explained very well by Dariusz Gertych in his extremely helpful article - 5 tips on how to use AngularJS with Rails that changed how we work. You can do it any way you like, just make sure JavaScript has access to this.

We won't be needing a secret because there's no way to keep it… well, secret, in a JavaScript application.

Grape-doorkeeper

Let's look at our current, authentication-free API:

moduleAPImoduleV1classUsers<Grape::APIincludeAPI::V1::Defaultsresource:usersdodesc"Return all users' emails, doesn't require authentication"get'/'doUser.all.pluck(:email)enddesc'Return current user, requires authentication'get'me'do'This will return current user in the near future'endendendendend

I believe it's pretty straightforward. Now we need to tell Grape that each endpoint requires authorization. We'll also define some helpers in order to use them later. It's generally a good idea to move it to Defaults or some other shared module, but - since we have only one resource to protect - I left it here for the sake of simplicity.

401 interceptor

Sooner or later Rails will return you the 401 (unauthorized) error code. It's good to do something with it. We might, for example, redirect the unauthorized user to a special page, explain what happened and suggest to log in.

Summary

That's it for now! I hope this post was helpful for you. OAuth Implicit Grant is probably not something you will be working on every day but when it finally presents itself, this article will have you covered.

Thank you and - as always - we'd love to hear your feedback.

Meet Ruby on Rails experts

We’ve been doing Ruby on Rails since 2010 and our services quality and technical expertise are confirmed by actual clients. Work with experts recognized as #1 Ruby on Rails company in the World in 2017 by Clutch.