lib/json/jwt.rb in json-jwt-1.2.4 vs lib/json/jwt.rb in json-jwt-1.3.0
- old
+ new
@@ -44,11 +44,11 @@
def header
@header ||= {}
end
def sign(private_key_or_secret, algorithm = :HS256)
- jws = JWS.new(self)
+ jws = JWS.new self
jws.alg = algorithm
jws.sign! private_key_or_secret
end
def verify(signature_base_string, public_key_or_secret = nil)
@@ -59,11 +59,11 @@
JWS.new(self).verify(signature_base_string, public_key_or_secret)
end
end
def encrypt(public_key_or_secret, algorithm = :RSA1_5, encryption_method = :'A128CBC-HS256')
- jwe = JWE.new(self)
+ jwe = JWE.new self
jwe.alg = algorithm
jwe.enc = encryption_method
jwe.encrypt! public_key_or_secret
end
@@ -75,12 +75,43 @@
].collect do |segment|
UrlSafeBase64.encode64 segment.to_s
end.join('.')
end
+ def as_json(options = {})
+ case options[:syntax]
+ when :general
+ {
+ payload: UrlSafeBase64.encode64(self.to_json),
+ signatures: [{
+ protected: UrlSafeBase64.encode64(header.to_json),
+ signature: UrlSafeBase64.encode64(signature.to_s)
+ }]
+ }
+ when :flattened
+ {
+ protected: UrlSafeBase64.encode64(header.to_json),
+ payload: UrlSafeBase64.encode64(self.to_json),
+ signature: UrlSafeBase64.encode64(signature.to_s)
+ }
+ else
+ super
+ end
+ end
+
class << self
- def decode(jwt_string, key_or_secret = nil)
+ def decode(input, key_or_secret = nil)
+ if input.is_a? Hash
+ decode_json_serialized input, key_or_secret
+ else
+ decode_compact_serialized input, key_or_secret
+ end
+ end
+
+ private
+
+ def decode_compact_serialized(jwt_string, key_or_secret)
case jwt_string.count('.') + 1
when JWS::NUM_OF_SEGMENTS # JWT / JWS
header, claims, signature = jwt_string.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment|
UrlSafeBase64.decode64 segment.to_s
end
@@ -113,14 +144,27 @@
end
rescue MultiJson::DecodeError
raise InvalidFormat.new("Invalid JSON Format")
end
- # # NOTE: Ugly hack to avoid this ActiveSupport 4.0 bug.
- # # https://github.com/rails/rails/issues/11087
- # def new_from_hash_copying_default(hash)
- # superclass.new_from_hash_copying_default hash
- # end
+ def decode_json_serialized(input, key_or_secret)
+ input = input.with_indifferent_access
+ header, payload, signature = if input[:signatures].present?
+ [
+ input[:signatures].first[:protected],
+ input[:payload],
+ input[:signatures].first[:signature]
+ ].collect do |segment|
+ segment
+ end
+ else
+ [:protected, :payload, :signature].collect do |key|
+ input[key]
+ end
+ end
+ jwt_string = [header, payload, signature].join('.')
+ decode_compact_serialized jwt_string, key_or_secret
+ end
end
end
end
require 'json/jose'
\ No newline at end of file