简体   繁体   中英

ruby on rails json rest api csrf token

I'm confused about the csrf token and these kind of stuffs..

I googled that

skip_before_action :verify_authenticity_token

this will skip the csrf issues for restapi

so i made a code like this in application_controller.rb

skip_before_action :verify_authenticity_token, :if => :json_request?
def json_request?
    request.format.json?
end

but my question is, is this all really all done? isn't this csrf token is for security protect? can i just skip this critical feature?

You can just add a subclass of ApplicationController and overwrite the protect_from_forgery method like so:

class API::V1::BaseController < ApplicationController
  protect_from_forgery with: :null_session

  respond_to :json

end

And then make your api controllers inherit from this one!

Check out APIs on Rails tutorial, it might help

In my case I use:

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

I used this in a project where there are no users or any other sensitive data, so there is no need to use auth tokens. But if you manage sensitive data you should use Auth tokens somehow (JWT, X-Auth-Token, etc).

Typically, people create a subcontroller of application controller to handle the API. Then API controllers subclass the API controller, and you can turn off csrf protection for only those controllers.

If you're building a real API, one that other people can use to get and post data, then you'd have some other means of authenticating that those users have permissions to either read, write, or both.

But if the API is just serving requests from your own html/javascript app, then you can simply include the csrf token with the ajax calls. WARNING: Can't verify CSRF token authenticity rails

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