GET请求授权headers(升级Rails-4.2到Rails-5.1)

GET request with authorization headers (upgrade Rails-4.2 to Rails-5.1)

因此,我们正在将 Rails 应用程序从 Rails 4.2 升级到 Rails 5.1。一切顺利,直到我也必须升级我们的测试。我们有一个 oauth_spec 文件,用于检查我们的身份验证过程是否一切正常。

我目前正在更改 Rspec 语法,因此一切正常,但我真的坚持我们的一项测试。它一直向我返回 401-Unauthorized,我想我已经阅读了在 Whosebug 上可以找到的所有相关内容。

这是我们在 4.2 中的测试:

it "grants access to a user's data when he sets an Authentication token as a request parameter" do
  data =
  {
    "grant_type" => "password",
    "password" => password,
    "username" => user.email
  }
  post('/oauth/token', data, {'HTTP_ACCEPT' => "application/json"})
  token = json["access_token"]
  get('/users/me', data, {'HTTP_ACCEPT' => "application/json", "Authorization" => "Bearer #{token}"})

  expect(response).to have_http_status(200)
  expect(json["email"]).to eq(user.email)
end

这是我目前得到的:

it "grants access to a user's data when he sets an Authentication token as a request parameter" do
  data =
  {
    "grant_type" => "password",
    "password" => password,
    "username" => user.email
  }
  post "/oauth/token", params: data
  token = json["access_token"]

  header = {"Authorization": "Bearer #{token}", "Accept": "application/json"}
  request.headers.merge!(header)
  get '/users/me'

  expect(response).to have_http_status(200)
  expect(json["email"]).to eq(user.email)
end

第一个 post 请求工作正常并给我我的承载。但是下一次休息,我总是得到:

Failure/Error: expect(response).to have_http_status(200) expected the response to have status code 200 but it was 401

有人知道我可以做些什么来完成这项工作吗?

您的原始代码:

get('/users/me', data, {'HTTP_ACCEPT' => "application/json", "Authorization" => "Bearer #{token}"})

您的新密码:

header = {"Authorization": "Bearer #{token}", "Accept": "application/json"}
request.headers.merge!(header)
get '/users/me'

在原始代码中,您传递了 data,即用户名和密码作为参数,而在 Rails5 代码中,您不再传递该数据。 可能 是 401 错误的原因之一,但鉴于规范标题,我认为不是。

我建议你这样做:

get '/users/me', headers: {"Authorization": "Bearer #{token}", "Accept": "application/json"}