views:

148

answers:

1

I am very new to Ruby on Rails and was never really big on writing JavaScript, so the built in helpers were like a tiny silce of heaven. However I have recently learned that using the helper methods creates "obtrusive javascript" so I am doing a tiny bit of refactoring to get all this messy code out of my view. I'm also using the Prototype API to figure out what all these functions do.

Right now, I have:

<%= periodically_call_remote(:url => {:action => "tablerefresh", :id => 1 }, :frequency => '5', :complete => "load('26', 'table1', request.responseText)")%>

Which produces:

<script type="text/javascript"> 
    //<![CDATA[
    new PeriodicalExecuter(function() {new Ajax.Request('/qrpsdrail/grids/tablerefresh/1', {asynchronous:true, evalScripts:true, onComplete:function(request){load('26', 'table1', request.responseText)}, parameters:'authenticity_token=' + encodeURIComponent('dfG7wWyVYEpelfdZvBWk7MlhzZoK7VvtT/HDi3w7gPM=')})}, 5)
    //]]>
</script>

My concern is that the "encodeURIComponent" and the presence of "authenticity_token" are generated by Rails. I'm assuming these are used to assure the validity of a request. (Ensuring a request comes from a currently active session?)

If that is the case, how can I implement this in application.js 'safely'? It seems that the built in method, although obtrusive, does add some beneficial security.

Thanks, in advance, to all who answer.

+2  A: 

Rails generates an authentication token to protect against XSS attacks. See: ActionController::RequestForgeryProtection You can turn it off but, you're right that it's much safer to use it.

The easiest workaround that comes to mind would be to just put the authentication token somewhere at the top of your page:

<% javascript_tag do %>
<%= "var AUTH_TOKEN=encodeURIComponent(#{form_authenticity_token.inspect});" %>
<% end %>

It's obtrusive but, at least then you could use the AUTH_TOKEN variable freely in your application.js file.

jdeseno
Thank you, that's exactly what I need to make this work.So really the only way to do this XSS request forgery protection is an obtrusive method? Since the .js files don't ever get parsed by Rails?
Robbie
jdeseno