Ramon Marques
Ramon Marques

Reputation: 3264

Rails can't verify CSRF token authenticity with cookies disabled

Is there any way to make protect_from_forgery work with the browser configured to not accept cookies?

My application works as expected when cookies are enabled, but I would like to make it work without cookies and with csrf protection.

Parameters: {"utf8"=>"✓", "authenticity_token"=>"nF9Qx0ZI16yHHG+yaxd+vojE0odr+24Es0yrR/CIjA9CbZ4dnNlMZh7YpzriyKcuw1BabdncX8bSfPjfMnmfDQ==", "password"=>"********", "commit"=>"Log in"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)



ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

actionpack (5.0.3) lib/action_controller/metal/request_forgery_protection.rb:195:in `handle_unverified_request'

Upvotes: 1

Views: 1240

Answers (1)

chumakoff
chumakoff

Reputation: 7024

The server compares the submitted authenticity_token to the value associated with the user’s session. So, without cookies enabled this will not work, since there is no associated session.

But, your problem might not be a problem at all. CSRF problem is that unwanted actions on a web application might be executed in which a user is currently authenticated (by session). If cookies are disabled, the user can't be authenticated and the user’s authentication can not be used to perform a CSRF attack.

Note that CSRF would still be possible if you are using HTTP Basic or HTTP Digest authentication. If you are using some other form of authentication without cookies, then CSRF isn't possible.

Furthermore, if unauthenticated users (it is when cookies disabled and you are not using some other form of authentication without cookies) can access this kind of actions, the CSRF protection is not really needed here, since there is actually nothing to protect. Also take into account that forgery protection is only useful for actions that have some effect on your app’s data. So, maybe you can just skip CSRF protection here.

Upvotes: 2

Related Questions