What is the proper way to grab Authorization header from controller request object?

I assumed that the API would be the same for the get method between a request and controller spec. In the controller spec, the third argument is a hash of sessions variables, not header variables. You can set the headers directly on the @request object like so:

describe Api::V2::CatsController do
  let(:user) { Fabricate(:user) }

  describe ".index" do
    let(:token) { OauthToken.create(user: user) }
    let(:auth_headers) { {
      'Authorization' => "Bearer #{token.access_token}",
      'HTTPS' => 'on'
    } }

    before do
      @request.env.merge!(auth_headers)
    end

    it "should be valid" do
      get :index, { format: :json, page_size: 1 }
      @json = JSON.parse(response.body)
      @json.should_not be_nil
    end
  end
end

Then the correct way to get the authorization header is using:

def bearer_token
  pattern = /^Bearer /
  header  = request.env["Authorization"] # <= env
  header.gsub(pattern, '') if header && header.match(pattern)
end

I found this.

https://github.com/rails/rails/commit/cf9d6a95e805bdddfa9c6b541631d51b3165bf23#diff-10b31f2069dfc4810229c8d60c3a4cda

in your controller, you can do something like this to get the header value.


def index

  header_value = request.authorization

end