ruby: jwt support

This commit is contained in:
Andrey Panov
2019-09-25 11:54:16 +03:00
parent 945c09f5d4
commit 1ecf16085e
5 changed files with 78 additions and 0 deletions

View File

@ -115,6 +115,30 @@ class HomeController < ApplicationController
end
file_data = JSON.parse(body)
if JwtHelper.is_enabled
inHeader = false
token = nil
if file_data["token"]
token = JwtHelper.decode(file_data["token"])
elsif request.headers["Authorization"]
hdr = request.headers["Authorization"]
hdr.slice!(0, "Bearer ".length)
token = JwtHelper.decode(hdr)
inHeader = true
else
raise "Expected JWT"
end
if !token
raise "Invalid JWT signature"
end
file_data = JSON.parse(token)
if inHeader
file_data = file_data["payload"]
end
end
status = file_data['status'].to_i
if status == 2 || status == 3 #MustSave, Corrupted

View File

@ -74,6 +74,11 @@ class FileModel
},
}
}
if JwtHelper.is_enabled
config["token"] = JwtHelper.encode(config)
end
return config
end

View File

@ -0,0 +1,41 @@
class JwtHelper
@jwt_secret = Rails.configuration.jwtSecret
class << self
def is_enabled
return @jwt_secret && !@jwt_secret.empty? ? true : false
end
def encode(payload)
header = { :alg => "HS256", :typ => "JWT" }
enc_header = Base64.urlsafe_encode64(header.to_json).remove("=")
enc_payload = Base64.urlsafe_encode64(payload.to_json).remove("=")
hash = Base64.urlsafe_encode64(calc_hash(enc_header, enc_payload)).remove("=")
return "#{enc_header}.#{enc_payload}.#{hash}"
end
def decode(token)
if !is_enabled
return ""
end
split = token.split(".")
hash = Base64.urlsafe_encode64(calc_hash(split[0], split[1])).remove("=")
if !hash.eql?(split[2])
return ""
end
return Base64.urlsafe_decode64(split[1])
end
private
def calc_hash(header, payload)
return OpenSSL::HMAC.digest("SHA256", @jwt_secret, "#{header}.#{payload}")
end
end
end

View File

@ -39,6 +39,12 @@ class ServiceConverter
req = Net::HTTP::Post.new(uri.request_uri)
req.add_field("Accept", "application/json")
req.add_field("Content-Type", "application/json")
if JwtHelper.is_enabled
payload["token"] = JwtHelper.encode(payload)
req.add_field("Authorization", "Bearer #{JwtHelper.encode({ :payload => payload })}")
end
req.body = payload.to_json
res = http.request(req)
data = res.body

View File

@ -43,5 +43,7 @@ module OnlineEditorsExampleRuby
Rails.configuration.urlApi="https://documentserver/web-apps/apps/api/documents/api.js"
Rails.configuration.urlPreloader="https://documentserver/web-apps/apps/api/documents/cache-scripts.html"
Rails.configuration.jwtSecret = ""
end
end