Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Moved the JWK key resolving to own class
- Loading branch information
Showing
4 changed files
with
56 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
# frozen_string_literal: true | ||
|
||
module JWT | ||
class JWKKeyFinder | ||
def initialize(options) | ||
jwks_or_loader = options[:jwks] | ||
@jwks = jwks_or_loader if jwks_or_loader.is_a?(Hash) | ||
@jwk_loader = jwks_or_loader if jwks_or_loader.respond_to?(:call) | ||
end | ||
|
||
def key_for(kid) | ||
raise JWT::DecodeError, 'No key id (kid) found from token headers' unless kid | ||
|
||
jwk = find_key(kid) | ||
|
||
if !jwk && reloadable? | ||
load_keys(invalidate: true) | ||
jwk = find_key(kid) | ||
end | ||
|
||
raise JWT::DecodeError, "Could not find public key for kid #{kid}" unless jwk | ||
|
||
JWT::JWK.import(jwk).keypair | ||
end | ||
|
||
private | ||
|
||
def jwks | ||
return @jwks if @jwks | ||
|
||
load_keys | ||
@jwks | ||
end | ||
|
||
def load_keys(opts = {}) | ||
@jwks = @jwk_loader.call(opts) | ||
end | ||
|
||
def find_key(kid) | ||
Array(jwks[:keys]).find { |key| key[:kid] == kid } | ||
end | ||
|
||
def reloadable? | ||
@jwk_loader | ||
end | ||
end | ||
end |