Sam*_*uel 6 ruby authentication ruby-on-rails rspec-rails
我有一个用户控制器,如下所示:
class Api::V1::UsersController < ApiController
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :find_user, only: [:show]
before_action :authenticate, only: [:destroy]
...
def destroy
if @user
@user.destroy
else
render json: { user: "not found" }, status: :not_found
end
end
private
...
def authenticate
authenticate_with_http_token do |token, options|
@user = User.find_by(token: token)
end
end
end
Run Code Online (Sandbox Code Playgroud)
我也有这个测试
describe "DELETE #destroy" do
before(:each) do
@user = FactoryBot.create :user
request.env['HTTP_AUTHORIZATION'] = @user.token
delete :destroy, params: { id: @user.id }
end
it { should respond_with 204 }
end
Run Code Online (Sandbox Code Playgroud)
每次我运行bundle exec rspec这个销毁方法的精确测试都会失败:
这是因为authenticate_with_http_token方法而发生的。我将令牌传递给 HTTP_AUTHORIZATION 标头,但authenticate_with_http_token方法看不到此令牌。我将authenticate控制器中的方法更改为:
def authenticate
@user = User.find_by(token: request.headers['HTTP_AUTHORIZATION'])
end
Run Code Online (Sandbox Code Playgroud)
测试顺利通过,一切正常。但我真的不认为明确地取出令牌request.headers是正确的方法,我想坚持使用authenticate_with_http_token. 我应该怎么做authenticate_with_http_token才能开始正常工作?
Authorization:Rails 使用该方法处理来自标头的以下任意格式的标记authenticate_with_http_token。
允许的格式:
Bearer "your_token"
Bearer your_token
Bearer token="your_token"
Bearer token=your_token
Token token="your_token"
Token token=your_token
Token "your_token"
Token your_token
Run Code Online (Sandbox Code Playgroud)