Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Rails CSRF tokens + Javascript

I have a line of javascript in one of my views for handling a POST request. In theory it works, but intermittently it adds a plus-sign into the CSRF token, which creates an authentication error.

JS in question:

webcam.set_api_url('<%= upload_users_path %>' + '?' + csrf_param + "=" + encodeURI(encodeURI(csrf_token)));

I don't know Javascript yet, but is there anything I can do to make this line more stable and get it to stop dropping in plus-signs?

Ex faulty request and error:

Started POST "/users/upload?authenticity_token=N0x/rDOgyC6AutbXzx8sZXLwDnB9zQ+NwWefXTpiSfE=" for 127.0.0.1 at 2013-06-04 01:06:34 -0400
  Processing by UsersController#upload as HTML
Parameters: {"authenticity_token"=>"N0x/rDOgyC6AutbXzx8sZXLwDnB9zQ NwWefXTpiSfE="}
  WARNING: Can't verify CSRF token authenticity

1 Answer

Zander,

I'm not sure why but the code is using the JavaScript function encodeURI() twice in that line, in your code you have encodeURI(encodeURI(csrf_token)). I don't think that is causing the issue but you only need to use the function once.

Could you provide the code on how the variable csrf_token is being determined? The function encodeURI() is encoding csrf_token to make it safe for a URL. It does not encode + signs as that is considered safe in a URL. I suspect the + sign is being randomly generated by the csrf_token. The w3schools documentation on encodeURI does a great job explaining this JavaScript function.

If you can post how the csrf_token variable is created, I think I can assist to prevent it from randomly generating a + sign into the string.

Thanks,
Codie