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 29633b1 commit 9a30b4e
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Take a look at the [upgrade guide](UPGRADING.md) for more details.

**Features:**
- JWT::EncodedToken#verify! method that bundles signature and claim validation [#647](https://github.com/jwt/ruby-jwt/pull/647) ([@anakinj](https://github.com/anakinj))
- Do not override the alg header if already given [#659](https://github.com/jwt/ruby-jwt/pull/659) ([@anakinj](https://github.com/anakinj))
- Your contribution here

**Fixes and enhancements:**
Expand Down
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
4 changes: 2 additions & 2 deletions spec/jwt/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -586,9 +586,9 @@
end

context 'when the alg value is given as a header parameter' do
it 'does not override the actual algorithm used' do
it 'overrides the actual algorithm used' do
headers = JSON.parse(JWT::Base64.url_decode(JWT.encode('Hello World', 'secret', 'HS256', { alg: 'HS123' }).split('.').first))
expect(headers['alg']).to eq('HS256')
expect(headers['alg']).to eq('HS123')
end

it 'should generate the same token' do
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 9a30b4e

Please sign in to comment.