Sha256: adf54bdd98a819d794b845f1decf7caeb1db4f4e05baf3ed3c6ee3cf14e9a316

Contents?: true

Size: 1.47 KB

Versions: 14

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.sso_config.base_uri}/",
          "sub" => "MOCK",
          "aud" => [NulogySSO.sso_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

14 entries across 14 versions & 1 rubygems

Version Path
nulogy_sso-2.6.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.5.1 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.5.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.4.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.3.1 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.3.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.2.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.1.3 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.1.2 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.1.1 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.1.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-2.0.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-1.0.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb
nulogy_sso-0.5.0 lib/nulogy_sso/test_utilities/jwt_test_helper.rb