Skip to content

Commit

Permalink
Add documentation for find_key
Browse files Browse the repository at this point in the history
  • Loading branch information
ritikesh authored and anakinj committed Jun 28, 2021
1 parent 7ca147e commit 4350e97
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
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

0 comments on commit 4350e97

Please sign in to comment.