Class: JSON::JWT
- Inherits:
-
Hash
show all
- Defined in:
- lib/json/jwt.rb
Direct Known Subclasses
JWE, JWS
Defined Under Namespace
Classes: Exception, InvalidFormat, VerificationFailed
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(claims) ⇒ JWT
Returns a new instance of JWT.
14
15
16
17
18
19
20
21
22
23
|
# File 'lib/json/jwt.rb', line 14
def initialize(claims)
@header = {
:typ => :JWT,
:alg => :none
}
[:exp, :nbf, :iat].each do |key|
claims[key] = claims[key].to_i if claims[key]
end
replace claims
end
|
Instance Attribute Details
Returns the value of attribute header.
8
9
10
|
# File 'lib/json/jwt.rb', line 8
def
@header
end
|
#signature ⇒ Object
Returns the value of attribute signature.
8
9
10
|
# File 'lib/json/jwt.rb', line 8
def signature
@signature
end
|
Class Method Details
.decode(jwt_string, public_key_or_secret = nil) ⇒ Object
58
59
60
61
62
63
64
65
66
67
68
69
70
|
# File 'lib/json/jwt.rb', line 58
def decode(jwt_string, public_key_or_secret = nil)
raise InvalidFormat.new('Invalid JWT Format. JWT should include 2 dots.') unless jwt_string.count('.') == 2
, claims, signature = jwt_string.split('.', 3).collect do |segment|
UrlSafeBase64.decode64 segment.to_s
end
signature_base_string = jwt_string.split('.')[0, 2].join('.')
jwt = new JSON.parse(claims)
jwt. = JSON.parse().with_indifferent_access
jwt.verify signature_base_string, signature, public_key_or_secret
jwt
rescue JSON::ParserError
raise InvalidFormat.new("Invalid JSON Format")
end
|
Instance Method Details
#[](key) ⇒ Object
48
49
50
51
52
53
54
55
|
# File 'lib/json/jwt.rb', line 48
def [](key)
if key.respond_to? :to_sym
super key.to_sym or
super key.to_s
else
super
end
end
|
#sign(private_key_or_secret, algorithm = :HS256) ⇒ Object
25
26
27
28
|
# File 'lib/json/jwt.rb', line 25
def sign(private_key_or_secret, algorithm = :HS256)
[:alg] = algorithm
JWS.new(self).sign!(private_key_or_secret)
end
|
#to_s ⇒ Object
38
39
40
41
42
43
44
45
46
|
# File 'lib/json/jwt.rb', line 38
def to_s
[
.to_json,
self.to_json,
signature
].collect do |segment|
UrlSafeBase64.encode64 segment.to_s
end.join('.')
end
|
#verify(signature_base_string, signature = '', public_key_or_secret = nil) ⇒ Object
30
31
32
33
34
35
36
|
# File 'lib/json/jwt.rb', line 30
def verify(signature_base_string, signature = '', public_key_or_secret = nil)
if [:alg].to_s == 'none'
signature == '' or raise VerificationFailed
else
JWS.new(self).verify(signature_base_string, signature, public_key_or_secret)
end
end
|