Sha256: 845de9894a0e5642451b8555ce04fab39f1a915f2dabd7802f136312dd849e5c

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

require "json/jwt"

module NulogySSO
  module TestUtilities

    # Test utilities that revolve around the JWT (JSON Web Token) protocool.
    # This class is mostly a helpful wrapper around this gem: https://github.com/nov/json-jwt
    class JwtTestHelper
      def initialize
        @private_key = OpenSSL::PKey::RSA.new(
          File.read(File.expand_path("key.pem", __dir__))
        )
        @public_key = private_key.public_key
      end

      attr_reader :private_key, :public_key

      def jwt(email, overrides = {})
        claim = {
          NulogySSO::JWT_EMAIL_KEY => email,
          "iss" => "#{NulogySSO.auth_config.base_uri}/",
          "sub" => "MOCK",
          "aud" => [NulogySSO.auth_config.audience],
          "exp" => (Time.now + 1.day).to_i
        }.merge(overrides)

        jwt = JSON::JWT.new(claim)
        jwt.header[:kid] = jwk["kid"]
        jwt = jwt.sign(private_key, :RS256)
        jwt.to_s
      end

      def jwk
        base_jwk_params = public_key.to_jwk.to_h
        JSON::JWK.new(
          base_jwk_params.merge(
            x5t: base_jwk_params["kid"],
            alg: "RS256",
            use: "sig",
            x5c: [certificate_der]
          )
        )
      end

      def jwks_json
        JSON::JWK::Set.new(jwk).to_json
      end

      private

      def certificate_der
        Base64.encode64(
          File.read(File.expand_path("cert.der", __dir__))
        ).gsub(/\n/, "")
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nulogy_sso-0.4.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-0.3.3 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-0.3.1 lib/nulogy_sso/test_utilities/jwt_test_helper.rb