Authorization strategy for Rails / Angular apps

April 21, 2013

I’ve seen a few strategies to handle user authorization for AngularJS apps using Rails as a backend. Basically, these break down into either letting Rails or Angular manage the authorization flow. To be clear, I’m talking about user interface feedback; you should definitely implement authorization checks (probably as a before_filter) in all of your Rails controllers before exposing resources to API consumers. Rather, as a user if I try to visit /users/1, but I’m not signed in then who is responsible for redirecting me to the right place and rendering the correct UI?

You could place this logic into AngularJS $routeChangeStart callbacks. However, I’ve found that this starts to get really complicated as it forces you to inject all sorts of session concerns into your client app.

Rather, I’ve opted to go with the following. First, I setup all of my Angular/Rails apps using the workflow I describe here. Next, I use a grunt plugin called Grunt Rename to rename the index.html file that is built and added to the /public folder to something like /public/angular_app.html.

What I’ve just done is now allow me to use the Rails routing layer for requests to the root of my web application. So, you can now set your root path to something like root to: "home#index", and then in your HomeController (using devise in this example):

def index
  if user_signed_in?
    set_csrf_cookie_for_angular
    render Rails.root.join('public', 'angular_app').to_s, layout: false
  else
    redirect_to new_user_session_path
  end
end

...

def set_csrf_cookie_for_angular
  cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end

Basically, what’s happening here is that if you’ve signed in through the Rails authentication layer then the controller just reads and responds with the angular_app.html file. Otherwise, it’s on to the sign in page for you. The cookies['XSRF-TOKEN] tells Angular how to issue properly signed AJAX requests that will pass Rails’ cross-site forgery inspection. For more on how Angular handles this automatically check out this part of the documentation.

Well, that’s all. Was this helpful for you? Do you use a different methodology? Drop me a line and let me know!

Looking to build a custom web application?

Contact me to start the conversation!