1

I'm currently running into a lot of issues with the CSRF token. Our current setup is a Ruby API and an Angular front-end, both live on a different domain.

The Ruby back-end solely serves as an API for the front-end.

I've spend a lot of time researching this problem, but I can't find a proper solution.

So far the solutions I've found are:

  • Generate the token and insert it into the DOM (Different domains, so can't do that)
  • Let the API return the CSRF token on a GET request (Doesn't seem to work, and it's not a good solution since I don't want to make an extra request just to get the token)

So I'm rather stuck here and not sure how to continue.

Is the current implementation just not working? How do other people create an API with oauth without running into this issue?

woutr_be
  • 9,532
  • 24
  • 79
  • 129

2 Answers2

0

Not sure if this will help but here is a sample of a simple todo api in ruby with angular as frontend, and i am using token for authentication generated after the user fills username and password.

https://github.com/sirfilip/todoapi/blob/master/app.rb (the api written in sinatra and sequel) https://github.com/sirfilip/todoapiclient/blob/master/public/js/angular-todoapi-plugin.js (angular client api service that is used for communication with the api)

sirfilip
  • 1,075
  • 1
  • 7
  • 10
  • Thanks for the example, but most of the things you are doing I was already doing. I'm returning the CSRF token upon request, I have a feeling Angular doesn't do anything with it. From reading about it, it seems Angular should handle this automatically. – woutr_be Nov 20 '14 at 09:56
0

TL;DR: Secure your rails API with the doorkeeper gem.

This SO post seems to be the accepted answer when your api and client exist on the same domain.

In the post they outline the angularJS docs http://docs.angularjs.org/api/ng.$http :

Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

To take advantage of this (CSRF Protection), your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on first HTTP GET request. On subsequent non-GET requests the server can verify that the cookie matches X-XSRF-TOKEN HTTP header

It seems that the security of storing and transferring the XSRF-TOKEN session cookie in this way hinges on having your api and your front-end be in the same domain. Since this is not the case, you may have to implement another form of authorization for any given client session, like OAUTH. I'd recommend taking a look at the doorkeeper gem. The gem will give you the ability to interact with your api as if you were any other client.

Community
  • 1
  • 1
zacatac
  • 69
  • 3