Skip to content

Commit

Permalink
Algorithm handling to token class
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Sep 29, 2024
1 parent fe7a3a3 commit 0a6d1f0
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 15 deletions.
13 changes: 2 additions & 11 deletions lib/jwt/decode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def verify_signature

raise JWT::DecodeError, 'No verification key available' unless @key

token.verify!(algorithms: allowed_and_valid_algorithms, verification_keys: @key)
token.verify_signature!(algorithms: allowed_and_valid_algorithms, verification_keys: @key)
end

def verify_algo
Expand Down Expand Up @@ -78,16 +78,7 @@ def allowed_algorithms
end

def resolve_allowed_algorithms
algs = given_algorithms.map { |alg| JWA.resolve(alg) }

sort_by_alg_header(algs)
end

# Move algorithms matching the JWT alg header to the beginning of the list
def sort_by_alg_header(algs)
return algs if algs.size <= 1

algs.partition { |alg| alg.valid_alg?(alg_in_header) }.flatten
given_algorithms.map { |alg| JWA.resolve(alg) }
end

def find_key(&keyfinder)
Expand Down
5 changes: 5 additions & 0 deletions lib/jwt/jwa.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def resolve(algorithm)

algorithm
end

def resolve_and_sort(algorithms:, preferred_algorithm:)
algs = Array(algorithms).map { |alg| JWA.resolve(alg) }
algs.partition { |alg| alg.valid_alg?(preferred_algorithm) }.flatten
end
end
end
end
12 changes: 8 additions & 4 deletions lib/jwt/token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ def signing_input
segments.first(2).join('.')
end

def verify!(algorithms:, verification_keys:)
return if Array(algorithms).any? do |algorithm|
def verify_signature!(algorithms:, verification_keys:)
return if valid_signature?(algorithms: algorithms, verification_keys: verification_keys)

raise JWT::VerificationError, 'Signature verification failed'
end

def valid_signature?(algorithms:, verification_keys:)
Array(JWA.resolve_and_sort(algorithms: algorithms, preferred_algorithm: header['alg'])).any? do |algorithm|
Array(verification_keys).any? do |verification_key|
algorithm.verify(data: signing_input, signature: signature, verification_key: verification_key)
end
end

raise JWT::VerificationError, 'Signature verification failed'
end

def parse_and_decode(segment)
Expand Down
2 changes: 2 additions & 0 deletions spec/spec_support/token.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

module SpecSupport
Token = Struct.new(:payload, keyword_init: true)
end

0 comments on commit 0a6d1f0

Please sign in to comment.