Getting "Can't verify CSRF token authenticity" with Rails api_only project
JiProchazka opened this issue ยท 6 comments
Hi,
I'm trying to use Knock with Rails api_only app.
I have started a new project with command rails new backend --api
(I started over twice to be sure, 5.2.0.rc1).
I have add this code:
# app/models/user.rb
class User < ApplicationRecord
has_secure_password
end
# app/controllers/user_token_controller.rb
class UserTokenController < Knock::AuthTokenController
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
include Knock::Authenticable
before_action :authenticate_user
before_action :set_default_format
private
def set_default_format
request.format = :json
end
end
# app/controller/tests_controller
class TestsController < ApplicationController
def index
render json: ['test1', 'test2']
end
end
When I run curl -v http://localhost:3000/tests/index
I get this, which is ok:
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /tests/index HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Content-Type: text/html
< Cache-Control: no-cache
< X-Request-Id: b4b86414-4e75-4bde-947c-6a0938797bb6
< X-Runtime: 0.001268
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
But when I want to ask for the token with this: curl --data "auth[email]=myemail@gmail.com&auth[password]=pass" http://localhost:3000/user_token
I'm getting:
{"status":422,"error":"Unprocessable Entity","exception":"#\u003cActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken\u003e,...."
and in my log there is Can't verify CSRF token authenticity. Completed 500 Internal Server Error in 96ms
Should not the command rails new backend --api
generate a project without CSRF?
Thanks
Ok, I just tried with Rails 5.1.4 and it is working. So it is something with 5.2.0.rc1..
Knock::AuthTokenController
is derived from ActionController::Base
. In Rails 5.2, protect_from_forgery
is included in ActionController::Base
(rails/rails@ec4a836)
Your example can be fixed this way:
# app/controllers/user_token_controller.rb
class UserTokenController < Knock::AuthTokenController
skip_before_action :verify_authenticity_token
end
It seems to me that #184 should fix it directly in the gem.
I had to use the fix stated in #205 , but it worked. Thanks!
I had to use both the fix @ledermann and the fix from #205 aswell to make my knock work.
Thanks for figuring it out people!
Why do you skip verify_authenticity_token
in that controller?
Why do you skip
verify_authenticity_token
in that controller?