Skip to content

Commit 806cf64

Browse files
committed
Tolerate Authorization headers in the form 'Bearer [token]'
1 parent 32a7a22 commit 806cf64

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

app/controllers/concerns/identifiable.rb

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ module Identifiable
99
end
1010

1111
def load_current_user
12-
token = request.headers['Authorization']
13-
return if token.blank?
12+
header = request.headers['Authorization']&.strip
13+
return if header.blank?
14+
15+
token = extract_token(header)
1416

1517
@current_user = User.from_token(token:)
1618
return if @current_user.blank?
@@ -19,4 +21,8 @@ def load_current_user
1921
RequestStore.store[:safeguarding_flag_users_by_token] ||= {}
2022
RequestStore.store[:safeguarding_flag_users_by_token][token] = @current_user
2123
end
24+
25+
def extract_token(header)
26+
header.sub(/^Bearer\s+/i, '')
27+
end
2228
end
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# frozen_string_literal: true
2+
3+
require 'rails_helper'
4+
5+
RSpec.describe Identifiable do
6+
subject(:extract_token) { identifiable.extract_token(header) }
7+
8+
let(:identifiable) { Class.new(ActionController::API) { include Identifiable }.new }
9+
10+
context 'when the header is a raw token' do
11+
let(:header) { nil }
12+
13+
it { is_expected.to eq('') }
14+
end
15+
16+
context 'when the header is a raw token' do
17+
let(:header) { 'secret-token' }
18+
19+
it { is_expected.to eq('secret-token') }
20+
end
21+
22+
context 'when the header is Bearer-prefixed' do
23+
let(:header) { 'Bearer secret-token' }
24+
25+
it { is_expected.to eq('secret-token') }
26+
end
27+
28+
context 'when the header uses a lowercase bearer prefix' do
29+
let(:header) { 'bearer secret-token' }
30+
31+
it { is_expected.to eq('secret-token') }
32+
end
33+
34+
context 'when the header is Bearer with no token' do
35+
let(:header) { 'Bearer ' }
36+
37+
it { is_expected.to eq('') }
38+
end
39+
end

0 commit comments

Comments
 (0)