Canna
Canna

Reputation: 3804

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?

Upvotes: 1

Views: 1938

Answers (3)

LightMan
LightMan

Reputation: 3575

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).

Upvotes: 2

kurenn
kurenn

Reputation: 1055

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

Upvotes: 1

evanbikes
evanbikes

Reputation: 4171

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

Upvotes: 1

Related Questions