security safe to disable csrf tokens for json rails calls?

假装没事ソ 提交于 2019-12-03 14:45:38
rook

What you are describing is very easy to exploit using Flash:

        var request:URLRequest = new URLRequest("http://stackoverflow.com"); 
        request.requestHeaders.push(new URLRequestHeader('Content-Type', 'application/json'));      
        request.data = unescape('{"a":1,"b":{"c":3}}');
        request.method = URLRequestMethod.POST;
        navigateToURL(request, '_blank');   

If you look at the CSRF prevention cheat sheet you can check the referer to make sure its from a domain you trust. If the referer is blank then it could be originating from a https url, so that should be considered a failure. Relying on Ruby's CSRF token is a stronger form a CSRF protection.

This is a fix for ajax

Get csrf_token from rails or if using something else, from meta

// js file
var csrf_token = $('meta[name=csrf-token]').attr('content');

or

//js.erb file
var csrf_token = "<%= request.session["<%= _csrf_token %>"] %>";

then add this to js

$("body").bind("ajaxSend", function(elm, xhr, s){
   if (s.type == "POST") {
    // place lines mentioned above here
    // line goes here...
    xhr.setRequestHeader('X-CSRF-Token', csrf_token);
   }
});

One approach you can take is to leave on CSRF checks but disable based on a http header being present. If your json requests have a JWT token, you can do something like this in the relevant controllers.

protect_from_forgery with: :exception, unless: -> { some_auth_token.valid? }

Form submissions won't be able to set a http header and thus csrf will protect against it.

You json requests should have an Authorization header to be secure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!