rails - “WARNING: Can't verify CSRF token authenticity” for json devise requests

前端 未结 10 2201
终归单人心
终归单人心 2020-11-27 10:11

How can I retrieve the CSRF token to pass with a JSON request?

I know that for security reasons Rails is checking the CSRF token on all the request types (including

10条回答
  •  不知归路
    2020-11-27 10:28

    EDIT:

    In Rails 4 I now use what @genkilabs suggests in the comment below:

    protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

    Which, instead of completely turning off the built in security, kills off any session that might exist when something hits the server without the CSRF token.


    skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }

    This would turn off the CSRF check for json posts/puts that have properly been marked as such.

    For example, in iOS setting the following to your NSURLRequest where "parameters" are your parameters:


    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"application/json" 
           forHTTPHeaderField:@"content-type"];
    
    [request setValue:@"application/json" 
           forHTTPHeaderField:@"accept"];
    
    [request setHTTPBody:[NSData dataWithBytes:[parameters UTF8String] 
                                                length:[parameters length]]];
    

提交回复
热议问题