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

Add documentation for find_key #426

Merged
merged 1 commit into from Jun 28, 2021
Merged
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
22 changes: 22 additions & 0 deletions README.md
Expand Up @@ -460,6 +460,28 @@ rescue JWT::InvalidSubError
end
```

### Finding a Key

To dynamically find the key for verifying the JWT signature, pass a block to the decode block. The block receives headers and the original payload as parameters. It should return with the key to verify the signature that was used to sign the JWT.

```ruby
issuers = %w[My_Awesome_Company1 My_Awesome_Company2]
iss_payload = { data: 'data', iss: issuers.first }

secrets = { issuers.first => hmac_secret, issuers.last => 'hmac_secret2' }

token = JWT.encode iss_payload, hmac_secret, 'HS256'

begin
# Add iss to the validation to check if the token has been manipulated
decoded_token = JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload|
secrets[payload['iss']]
end
rescue JWT::InvalidIssuerError
# Handle invalid token, e.g. logout user or deny access
end
```

### JSON Web Key (JWK)

JWK is a JSON structure representing a cryptographic key. Currently only supports RSA public keys.
Expand Down
15 changes: 15 additions & 0 deletions spec/integration/readme_examples_spec.rb
Expand Up @@ -226,6 +226,21 @@
end.not_to raise_error
end

it 'find_key' do
issuers = %w[My_Awesome_Company1 My_Awesome_Company2]
iss_payload = { data: 'data', iss: issuers.first }

secrets = { issuers.first => hmac_secret, issuers.last => 'hmac_secret2' }

token = JWT.encode iss_payload, hmac_secret, 'HS256'

expect do
# Add iss to the validation to check if the token has been manipulated
JWT.decode(token, nil, true, { iss: issuers, verify_iss: true, algorithm: 'HS256' }) do |_headers, payload|
secrets[payload['iss']]
end
end.not_to raise_error
end

it 'JWK' do
jwk = JWT::JWK.new(OpenSSL::PKey::RSA.new(2048))
Expand Down