Skip to content

Instantly share code, notes, and snippets.

@xifengzhu
Created September 14, 2017 08:54
Show Gist options
  • Save xifengzhu/b135a0eaad836f792c8507117ae3a42c to your computer and use it in GitHub Desktop.
Save xifengzhu/b135a0eaad836f792c8507117ae3a42c to your computer and use it in GitHub Desktop.
JWT
require 'jwt'
class JsonWebToken
# Encodes and signs JWT Payload with expiration
def self.encode(payload)
payload.reverse_merge!(meta)
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end
# Decodes the JWT with the signed secret
def self.decode(token)
JWT.decode(token, Rails.application.secrets.secret_key_base)
end
# Validates the payload hash for expiration and meta claims
def self.valid_payload(payload)
if expired(payload) || payload['client'] != meta[:client]
return false
else
return true
end
end
# Default options to be encoded in the token
def self.meta
{
expired_at: 7.days.from_now.to_i,
client: 'wechat_app'
}
end
# Validates if the token is expired by exp parameter
def self.expired(payload)
Time.at(payload['expired_at']) < Time.now
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment