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:
````ruby
class User < ApplicationRecord
has_secure_password
end
ruby
class UserTokenController < Knock::AuthTokenController
end
ruby
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
ruby
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:
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][email protected]&auth[password]=pass" http://localhost:3000/user_token` I'm getting:
{"status":422,"error":"Unprocessable Entity","exception":"#u003cActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityTokenu003e,...."
```and in my log there isCan'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 (https://github.com/rails/rails/commit/ec4a836919c021c0a5cf9ebeebb4db5e02104a55)
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_tokenin that controller?
Most helpful comment
Knock::AuthTokenControlleris derived fromActionController::Base. In Rails 5.2,protect_from_forgeryis included inActionController::Base(https://github.com/rails/rails/commit/ec4a836919c021c0a5cf9ebeebb4db5e02104a55)Your example can be fixed this way:
It seems to me that #184 should fix it directly in the gem.