Skip to content

Commit

Permalink
Possibility to give the expiration time on the JWT class
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Jan 13, 2022
1 parent c37595d commit 1ef54ff
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
8 changes: 7 additions & 1 deletion lib/jwt/dsl/encode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ def encode_payload(&block)
@encode_payload
end

def expiration(value = nil)
@expiration = value unless value.nil?
@expiration
end

def encode!(payload, options = {})
Internals.encode!(payload, options, self)
end
Expand All @@ -29,7 +34,8 @@ def build_options(payload, options, context)
key: options[:key] || context.signing_key,
encode_payload_proc: context.encode_payload,
headers: options[:headers],
algorithm: context.algorithm
algorithm: context.algorithm,
expiration: context.expiration
}

if opts[:algorithm].is_a?(String) && opts[:key].nil?
Expand Down
11 changes: 10 additions & 1 deletion lib/jwt/encode.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def segments
attr_reader :headers, :options, :algorithm, :alg

def payload
options[:payload]
@payload ||= append_exp(options[:payload])
end

def key
Expand Down Expand Up @@ -84,6 +84,15 @@ def validate_claims!
ClaimsValidator.new(payload).validate!
end

def append_exp(payload)
return payload unless (expiration = options[:expiration])
return payload if payload.key?('exp') || payload.key?(:exp)

payload['exp'] = Time.now.to_i + expiration

payload
end

class << self
def encode(data)
Base64.urlsafe_encode64(JWT::JSON.generate(data), padding: false)
Expand Down
13 changes: 13 additions & 0 deletions spec/dsl/encode_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,18 @@
expect(jwt_class.encode!(payload)).to eq(::JWT.encode(payload, secret, 'HS256'))
end
end

context 'when expiration is set on the class and is negative' do
before do
jwt_class.algorithm('HS256')
jwt_class.expiration(-10)
jwt_class.signing_key(secret)
end

it 'will only generate expired tokens' do
token = jwt_class.encode!(payload)
expect { jwt_class.decode!(token) }.to raise_error(JWT::ExpiredSignature, 'Signature has expired')
end
end
end
end

0 comments on commit 1ef54ff

Please sign in to comment.