Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve JWK kid on import #320

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/jwt/jwk/rsa.rb
Expand Up @@ -8,19 +8,21 @@ class RSA
extend Forwardable

attr_reader :keypair
attr_reader :jwk_kid

def_delegators :keypair, :private?, :public_key

BINARY = 2
KTY = 'RSA'.freeze

def initialize(keypair)
def initialize(keypair, kid = nil)
raise ArgumentError, 'keypair must be of type OpenSSL::PKey::RSA' unless keypair.is_a?(OpenSSL::PKey::RSA)

@jwk_kid = kid
@keypair = keypair
end

def kid
return jwk_kid if jwk_kid
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to have this method as something like:

def kid
  @kid ||= generate_from_public_key
end

Then we can just set the instance variable @kid in the constructor.

sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer.new(public_key.n),
OpenSSL::ASN1::Integer.new(public_key.e)])
OpenSSL::Digest::SHA256.hexdigest(sequence.to_der)
Expand All @@ -40,7 +42,7 @@ def self.import(jwk_data)
imported_key.set_key(OpenSSL::BN.new(::Base64.urlsafe_decode64(jwk_data[:n]), BINARY),
OpenSSL::BN.new(::Base64.urlsafe_decode64(jwk_data[:e]), BINARY),
nil)
self.new(imported_key)
self.new(imported_key, jwk_data[:kid])
end
end
end
Expand Down
7 changes: 7 additions & 0 deletions spec/jwk_spec.rb
Expand Up @@ -24,6 +24,13 @@
expect { subject }.to raise_error(JWT::JWKError)
end
end

context 'when keypair with defined kid is imported' do
it 'returns the predefined kid if jwt_data contains a kid' do
params[:kid] = "CUSTOM_KID"
expect(subject.export).to eq(params)
end
end
end

describe '.to_jwk' do
Expand Down