Search code examples
ruby-on-railsrspecdoorkeeper

Invalid access_token when using RSpec request specs to authorize a request


I'm trying to test CredentialsController, which works fine in production, using RSpec request specs.

Code

Controller

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

(GET /me routes to CredentialsController#me.)

Request Specs

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

The unauthorized test passes, but the authorized test fails:

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

The headers indicate a problem with the token:

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

token looks okay to me, though:

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

Factories

Access Token

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

Application

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

User

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

Questions

  • Why am I getting invalid_token on this request?
  • Do my Doorkeeper factories look correct?

Solution

  • I was passing the token wrong. Instead of:

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

    I had to use:

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