Skip to content

Commit

Permalink
Allow alg header to be given
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Dec 28, 2024
1 parent f9fac27 commit 0a24395
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/jwt/token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def sign!(algorithm:, key:)
raise ::JWT::EncodeError, 'Token already signed' if @signature

JWA.resolve(algorithm).tap do |algo|
header.merge!(algo.header)
header.merge!(algo.header) { |_key, old, _new| old }
@signature = algo.sign(data: signing_input, signing_key: key)
end

Expand Down
9 changes: 9 additions & 0 deletions spec/jwt/encoded_token_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@
end
end

context 'when header has invalid alg value' do
let(:header) { { 'alg' => 'HS123' } }

it 'does not raise' do
expect(token.header).to eq(header)
expect(token.verify_signature!(algorithm: 'HS256', key: 'secret')).to eq(nil)
end
end

context 'when payload is detached' do
let(:encoded_token) { detached_payload_token.jwt }

Expand Down
12 changes: 12 additions & 0 deletions spec/jwt/token_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@
expect { token.jwt }.to raise_error(JWT::EncodeError)
end
end

context 'when alg is given in header' do
let(:header) { { 'alg' => 'HS123' } }

before do
token.sign!(algorithm: 'HS256', key: 'secret')
end

it 'returns a signed and encoded token' do
expect(JWT::EncodedToken.new(token.jwt).header).to eq({ 'alg' => 'HS123' })
end
end
end

describe '#detach_payload!' do
Expand Down

0 comments on commit 0a24395

Please sign in to comment.