Yessiest
3 months ago
6 changed files with 76 additions and 18 deletions
-
1lib/landline.rb
-
9lib/landline/dsl/methods_path.rb
-
2lib/landline/dsl/methods_probe.rb
-
8lib/landline/util/cookie.rb
-
54lib/landline/util/jwt.rb
-
20lib/landline/util/parseutils.rb
@ -0,0 +1,54 @@ |
|||
# frozen_string_literal: true |
|||
|
|||
require 'openssl' |
|||
require 'json' |
|||
require 'base64' |
|||
|
|||
if RUBY_ENGINE == 'jruby' # fix for JRuby |
|||
OpenSSL::HMAC.define_singleton_method(:base64digest) do |*args| |
|||
Base64.strict_encode64(OpenSSL::HMAC.digest(*args)).strip |
|||
end |
|||
end |
|||
|
|||
module Landline |
|||
module Util |
|||
# JSON Web Token construction class |
|||
class JWT |
|||
# Create a new JWT token wrapper |
|||
# @param data [Hash, Array] JSON-formattable data |
|||
# @param halgo [String] Name of the hash algorithm to use |
|||
def initialize(data, halgo = "SHA256") |
|||
@halgo = halgo |
|||
@data = data |
|||
end |
|||
|
|||
# Construct a string representation of the current token |
|||
# @param key [String] |
|||
# @return [String] |
|||
def make(key) |
|||
jsondata = @data.to_json |
|||
[ |
|||
{ |
|||
"hash" => @halgo |
|||
}.to_json, |
|||
jsondata, |
|||
OpenSSL::HMAC.digest(@halgo, key, jsondata) |
|||
].map(&Base64.method(:strict_encode64)).map(&:strip).join "&" |
|||
end |
|||
|
|||
# Construct an object from string |
|||
# @param input [String] |
|||
# @param key [String] |
|||
# @return [JWT, nil] returns nil if verification couldn't complete |
|||
def self.from_string(input, key) |
|||
halgoj, dataj, sig = input.split("&").map(&Base64.method(:strict_decode64)) |
|||
halgo = JSON.parse(halgoj)["hash"] |
|||
return nil if OpenSSL::HMAC.digest(halgo, key, dataj) != sig |
|||
|
|||
new(JSON.parse(dataj), halgo) |
|||
end |
|||
|
|||
attr_accessor :data |
|||
end |
|||
end |
|||
end |
Write
Preview
Loading…
Cancel
Save
Reference in new issue