gpt4 book ai didi

ruby-on-rails - 使用 RSpec 请求规范授权请求时 access_token 无效

转载 作者:行者123 更新时间:2023-12-02 00:05:32 26 4
gpt4 key购买 nike

我正在尝试测试 CredentialsController ,它在生产中运行良好,使用 RSpec 请求规范。

代码

Controller

class CredentialsController < ApplicationController
before_action :doorkeeper_authorize!
def me
render json: current_user
end
end

( GET /me 路由到 CredentialsController#me 。)

请求规范

describe 'Credentials', type: :request do
context 'unauthorized' do
it "should 401" do
get '/me'
expect(response).to have_http_status(:unauthorized)
end
end

context 'authorized' do
let!(:application) { FactoryBot.create(:application) }
let!(:user) { FactoryBot.create(:user) }
let!(:token) { FactoryBot.create(:access_token, application: application, resource_owner_id: user.id) }

it 'succeeds' do
get '/me', params: {}, headers: {access_token: token.token}
expect(response).to be_successful
end
end
end

非授权测试通过,但授权测试失败:

expected #<ActionDispatch::TestResponse:0x00007fd339411248 @mon_mutex=#<Thread::Mutex:0x00007fd339410438>, @mo..., @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil>>.successful? to return true, got false

header 表明 token 有问题:

0> response.headers['WWW-Authenticate']
=> "Bearer realm=\"Doorkeeper\", error=\"invalid_token\", error_description=\"The access token is invalid\""

token不过,我觉得还不错:

0> token
=> #<Doorkeeper::AccessToken id: 7, resource_owner_id: 8, application_id: 7, token: "mnJh2wJeEEDe0G-ukNIZ6oupKQ7StxJqKPssjZTWeAk", refresh_token: nil, expires_in: 7200, revoked_at: nil, created_at: "2020-03-19 20:17:26", scopes: "public", previous_refresh_token: "">

0> token.acceptable?(Doorkeeper.config.default_scopes)
=> true

工厂

访问 token

FactoryBot.define do
factory :access_token, class: "Doorkeeper::AccessToken" do
application
expires_in { 2.hours }
scopes { "public" }
end
end

申请

FactoryBot.define do
factory :application, class: "Doorkeeper::Application" do
sequence(:name) { |n| "Project #{n}" }
sequence(:redirect_uri) { |n| "https://example#{n}.com" }
end
end

用户

FactoryBot.define do
factory :user do
sequence(:email) { |n| "email#{n}@example.com" }
password { "test123" }
password_confirmation { "test123" }
end
end

问题

  • 为什么我得到 invalid_token根据这个要求?
  • 我的 Doorkeeper 工厂看起来正确吗?

最佳答案

我错误地传递了 token 。而不是:

get '/me', params: {}, headers: {access_token: token.token}

我必须使用:

get '/me', params: {}, headers: { 'Authorization': 'Bearer ' + token.token}

关于ruby-on-rails - 使用 RSpec 请求规范授权请求时 access_token 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com