Zhang
Zhang

Reputation: 11607

Rails 5 set Authorization header

I got JSON Web Token login going but am in the process of fixing my Rails 5 Controller tests.

I am trying to pass my JWT auth token to my GET request header.

So far, in my User Controller test, I have this test:

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

So far that doesn't work, I get response not authenticated.

If I change it to like so:

 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

I get this expected response:

response = {"users":[{"id":298486374,"name":"MyString","email":"MyString","cats":[]},{"id":980190962,"name":"MyString","email":"MyString","cats":[]},{"id":980190963,"name":"Bob","email":"[email protected]","cats":[]}]}

but I also get a DEPRECATED WARNING:

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

So what is the recommended way to set HTTP Authorization header in Rails 5 ?

Upvotes: 4

Views: 5898

Answers (1)

jgraft
jgraft

Reputation: 938

You need to include the params and headers key in the arguments see here.

get users_path, params: {}, headers: { HTTP_AUTHORIZATION: "JWT #{auth_token}" }

You first example probably isn't working because you are setting the JWT on Authorization and not HTTP_AUTHORIZATION.

 request.headers['HTTP_AUTHORIZATION'] = "JWT #{auth_token}"   

Upvotes: 4

Related Questions