简体   繁体   中英

Rails documentation on RequestForgeryProtection for API requests

I am reading notes on protect_from_forgery http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html and these few lines really confuse me.

It's important to remember that XML or JSON requests are also affected and if you're building an API you should change forgery protection method in ApplicationController (by default: :exception):

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

CSRF protection is turned on with the protect_from_forgery method. By default protect_from_forgery protects your session with :null_session method, which provides an empty session during request.

It was saying exception is the default for protect_from_forgery unless: -> { request.format.json? } protect_from_forgery unless: -> { request.format.json? } but later saying null_session is the default for protect_from_forgery .

Does it mean that if we are using protect_from_forgery unless: -> { request.format.json? } protect_from_forgery unless: -> { request.format.json? } , exception will become the default? And if we are using protect_from_forgery , null_session will become the default?

Any help is greatly appreciated.

The documentation is accurate, if a bit confusing; each statement refers to a different "default" behavior. What the first statement means is that the default for new Rails apps is to generate your ApplicationController with this line:

protect_from_forgery :exception

What the second statement means, though, is that for the protect_from_forgery method, the default value of the parameter if omitted is :null_session . So if you were to remove :exception from your ApplicationController, ie, you just had:

protect_from_forgery

Then the behavior used would be that of :null_session (see the implementation for proof).

So the first statement refers to the default generated code for new Rails apps; the second statement refers to the default value of the method itself. It's weird that they're different, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM