class SelfSDK::JwtService
Attributes
id[R]
key[R]
key_id[R]
Public Class Methods
new(app_id, app_key)
click to toggle source
Jwt initializer
@param app_id [string] the app id. @param app_key [string] the app api key provided by developer portal.
# File lib/jwt_service.rb, line 16 def initialize(app_id, app_key) @id = app_id parts = app_key.split(':') if parts.length > 1 @key_id = parts[0] @key = parts[1] else @key_id = "1" @key = app_key end end
Public Instance Methods
auth_token()
click to toggle source
Generates the auth_token
based on the app's private key.
# File lib/jwt_service.rb, line 83 def auth_token payload = header + "." + encode({ jti: SecureRandom.uuid, cid: SecureRandom.uuid, typ: 'auth.token', iat: (SelfSDK::Time.now - 5).to_i, exp: (SelfSDK::Time.now + 60).to_i, iss: @id, sub: @id}.to_json) signature = sign(payload) "#{payload}.#{signature}" end
decode(input)
click to toggle source
Base64 decodes the input string
@param input [string] the string to be decoded.
# File lib/jwt_service.rb, line 58 def decode(input) Base64.urlsafe_decode64(input) end
encode(input)
click to toggle source
Encodes the input with base64
@param input [string] the string to be encoded.
# File lib/jwt_service.rb, line 51 def encode(input) Base64.urlsafe_encode64(input, padding: false) end
parse(input)
click to toggle source
# File lib/jwt_service.rb, line 44 def parse(input) JSON.parse(input, symbolize_names: true) end
prepare(input)
click to toggle source
Prepares a jwt object based on an input
@param input [string] input to be prepared
# File lib/jwt_service.rb, line 31 def prepare(input) signed(input).to_json end
sign(input)
click to toggle source
Signs the given input with the configured Ed25519 key.
@param input [string] the string to be signed.
# File lib/jwt_service.rb, line 65 def sign(input) signing_key = Ed25519::SigningKey.new(decode(@key)) signature = signing_key.sign(input) encode(signature) end
signed(input)
click to toggle source
# File lib/jwt_service.rb, line 35 def signed(input) payload = encode(input.to_json) { payload: payload, protected: header, signature: sign("#{header}.#{payload}") } end
verify(payload, key)
click to toggle source
# File lib/jwt_service.rb, line 71 def verify(payload, key) verify_key = Ed25519::VerifyKey.new(decode(key)) if verify_key.verify(decode(payload[:signature]), "#{payload[:protected]}.#{payload[:payload]}") return true end false rescue StandardError => e SelfSDK.logger.info e false end
Private Instance Methods
header()
click to toggle source
# File lib/jwt_service.rb, line 98 def header encode({ alg: "EdDSA", typ: "JWT", kid: "#{@key_id}" }.to_json) end