Rails 5 设置授权 header
Rails 5 set Authorization header
我得到了 JSON Web 令牌登录,但我正在修复我的 Rails 5 个控制器测试。
我正在尝试将我的 JWT 身份验证令牌传递给我的 GET 请求 header。
到目前为止,在我的用户控制器测试中,我有这个测试:
test "users should return list of users" do
User.create(@bob)
auth_token = log_in_as(@bob)
request.headers['Authorization'] = "JWT #{auth_token}"
get users_path
assert_response :success
assert_not response.body.empty?
end
到目前为止这不起作用,我收到了回复 not authenticated
。
如果我改成这样:
test "users should return list of users" do
User.create(@bob)
auth_token = log_in_as(@bob)
get users_path, nil, { HTTP_AUTHORIZATION: "JWT #{auth_token}" }
puts "response = #{response.body}"
assert_response :success
assert_not response.body.empty?
end
我收到了预期的回复:
response = {"users":[{"id":298486374,"name":"MyString","email":"MyString","cats":[]},{"id":980190962,"name":"MyString","email":"MyString","cats":[]},{"id":980190963,"name":"Bob","email":"bob@gmail.com","cats":[]}]}
但我也收到了已弃用的警告:
DEPRECATION WARNING: ActionDispatch::IntegrationTest HTTP request
methods will accept only the following keyword arguments in future
Rails versions: params, headers, env, xhr
Examples:
get '/profile', params: { id: 1 }, headers: { 'X-Extra-Header' =>
'123' }, env: { 'action_dispatch.custom' => 'custom' }, xhr: true
那么在 Rails 5 中设置 HTTP 授权 header 的推荐方法是什么?
您需要在参数中包含 params 和 headers 键 see here。
get users_path, params: {}, headers: { HTTP_AUTHORIZATION: "JWT #{auth_token}" }
您的第一个示例可能无法正常工作,因为您将 JWT 设置为授权而不是 HTTP_AUTHORIZATION。
request.headers['HTTP_AUTHORIZATION'] = "JWT #{auth_token}"
我得到了 JSON Web 令牌登录,但我正在修复我的 Rails 5 个控制器测试。
我正在尝试将我的 JWT 身份验证令牌传递给我的 GET 请求 header。
到目前为止,在我的用户控制器测试中,我有这个测试:
test "users should return list of users" do
User.create(@bob)
auth_token = log_in_as(@bob)
request.headers['Authorization'] = "JWT #{auth_token}"
get users_path
assert_response :success
assert_not response.body.empty?
end
到目前为止这不起作用,我收到了回复 not authenticated
。
如果我改成这样:
test "users should return list of users" do
User.create(@bob)
auth_token = log_in_as(@bob)
get users_path, nil, { HTTP_AUTHORIZATION: "JWT #{auth_token}" }
puts "response = #{response.body}"
assert_response :success
assert_not response.body.empty?
end
我收到了预期的回复:
response = {"users":[{"id":298486374,"name":"MyString","email":"MyString","cats":[]},{"id":980190962,"name":"MyString","email":"MyString","cats":[]},{"id":980190963,"name":"Bob","email":"bob@gmail.com","cats":[]}]}
但我也收到了已弃用的警告:
DEPRECATION WARNING: ActionDispatch::IntegrationTest HTTP request methods will accept only the following keyword arguments in future Rails versions: params, headers, env, xhr
Examples:
get '/profile', params: { id: 1 }, headers: { 'X-Extra-Header' => '123' }, env: { 'action_dispatch.custom' => 'custom' }, xhr: true
那么在 Rails 5 中设置 HTTP 授权 header 的推荐方法是什么?
您需要在参数中包含 params 和 headers 键 see here。
get users_path, params: {}, headers: { HTTP_AUTHORIZATION: "JWT #{auth_token}" }
您的第一个示例可能无法正常工作,因为您将 JWT 设置为授权而不是 HTTP_AUTHORIZATION。
request.headers['HTTP_AUTHORIZATION'] = "JWT #{auth_token}"