设计和设计令牌授权
Devise and Devise Token Auth
我正在尝试制作 rails 网络应用程序以及 rails API 移动应用程序。为此,我将 Devise 与 Devise 令牌身份验证一起使用。
我按照 Devise token auth gem 中的说明配置了路由,这样我就可以拥有常规 Devise 和 Devise auth 令牌的路由。
我有两个问题:
- 当我将 include DeviseTokenAuth::Concerns::SetUserByToken 添加到 application_controller 时,它会覆盖 Devise
authenticate_user!
并且在 Web 端我正在使用令牌进行身份验证。
可能的解决方案:我创建了单独的 ApiApplicationController,API 控制器从中继承。
class ApiApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
protect_from_forgery with: :null_session
end
- 对于我在 curl 中对 API 执行的每个 POST 请求,我需要添加 CSRF 令牌。
可能的解决方案:我可以在 protect_from_forgery with: :null_session
之后添加到 ApplictionController 和 ApiApplicationController if: Proc.new { |c| c.request.format == 'application/json' }
我以前遇到过和你一样的问题,我的解决方案目前有效:
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session, if: ->{request.format.json?}
end
# api_application_controller.rb
class ApiApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :authenticate_user!
end
我正在尝试制作 rails 网络应用程序以及 rails API 移动应用程序。为此,我将 Devise 与 Devise 令牌身份验证一起使用。
我按照 Devise token auth gem 中的说明配置了路由,这样我就可以拥有常规 Devise 和 Devise auth 令牌的路由。
我有两个问题:
- 当我将 include DeviseTokenAuth::Concerns::SetUserByToken 添加到 application_controller 时,它会覆盖 Devise
authenticate_user!
并且在 Web 端我正在使用令牌进行身份验证。
可能的解决方案:我创建了单独的 ApiApplicationController,API 控制器从中继承。
class ApiApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
protect_from_forgery with: :null_session
end
- 对于我在 curl 中对 API 执行的每个 POST 请求,我需要添加 CSRF 令牌。
可能的解决方案:我可以在 protect_from_forgery with: :null_session
if: Proc.new { |c| c.request.format == 'application/json' }
我以前遇到过和你一样的问题,我的解决方案目前有效:
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session, if: ->{request.format.json?}
end
# api_application_controller.rb
class ApiApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :authenticate_user!
end