Commit f777c28

mo <mo@mokhan.ca>
2017-11-07 21:33:48
include JWT token in SAML Response.
1 parent eb710f9
app/models/bearer_token.rb
@@ -0,0 +1,32 @@
+class BearerToken
+  def initialize(private_key = Saml::Kit.configuration.signing_private_key)
+    @private_key = private_key
+    @public_key = private_key.public_key
+  end
+
+  def encode(payload)
+    JWT.encode(timestamps.merge(payload), private_key, 'RS256')
+  end
+
+  def decode(token)
+    JWT.decode(token, public_key, true, { algorithm: 'RS256' })[0].with_indifferent_access
+  rescue
+    {}
+  end
+
+  private
+
+  attr_reader :private_key, :public_key
+
+  def timestamps
+    { exp: expiration.to_i, iat: issued_at.to_i }
+  end
+
+  def issued_at
+    Time.current
+  end
+
+  def expiration
+    1.hour.from_now
+  end
+end
app/models/user.rb
@@ -17,9 +17,14 @@ class User < ApplicationRecord
       id: uuid,
       email: email,
       created_at: created_at,
+      access_token: access_token,
     }
   end
 
+  def access_token
+    BearerToken.new.encode(id: uuid)
+  end
+
   def self.login(email, password)
     return if email.blank? || password.blank?
 
Gemfile
@@ -59,3 +59,4 @@ gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
 gem 'dotenv-rails'
 gem 'saml-kit', path: '../saml-kit'
 gem 'rails-assets-bootstrap', source: 'https://rails-assets.org'
+gem 'jwt'
Gemfile.lock
@@ -93,6 +93,7 @@ GEM
     jbuilder (2.7.0)
       activesupport (>= 4.2.0)
       multi_json (>= 1.2)
+    jwt (2.0.0)
     listen (3.1.5)
       rb-fsevent (~> 0.9, >= 0.9.4)
       rb-inotify (~> 0.9, >= 0.9.7)
@@ -237,6 +238,7 @@ DEPENDENCIES
   dotenv-rails
   ffaker
   jbuilder (~> 2.5)
+  jwt
   listen (>= 3.0.5, < 3.2)
   puma (~> 3.7)
   rails (~> 5.1.4)