Class: OmniAuth::Strategies::JWT

Inherits:
Object
  • Object
show all
Includes:
OmniAuth::Strategy
Defined in:
lib/omniauth/strategies/jwt.rb

Direct Known Subclasses

Jwt

Defined Under Namespace

Classes: BadJwt, ClaimInvalid

Instance Method Summary collapse

Instance Method Details

#callback_phaseObject



96
97
98
99
100
101
102
# File 'lib/omniauth/strategies/jwt.rb', line 96

def callback_phase
  super
rescue BadJwt => e
  fail! "bad_jwt", e
rescue ClaimInvalid => e
  fail! :claim_invalid, e
end

#decodedObject

Raises:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/omniauth/strategies/jwt.rb', line 29

def decoded
  begin
    secret = if defined?(OpenSSL)
      case options.algorithm
      when "RS256", "RS384", "RS512"
        OpenSSL::PKey::RSA.new(options.secret).public_key
      when "ES256", "ES384", "ES512"
        ec_key(options.secret)
      when "HS256", "HS384", "HS512"
        options.secret
      else
        raise NotImplementedError, "Unsupported algorithm: #{options.algorithm}"
      end
    else
      options.secret
    end

    # JWT.decode can handle either algorithms or algorithm, but not both.
    default_algos = options.decode_options.key?(:algorithms) ? options.decode_options[:algorithms] : [options.algorithm]
    @decoded ||= ::JWT.decode(
      request.params["jwt"],
      secret,
      true,
      options.decode_options.merge(
        {
          algorithms: default_algos,
          jwks: options.jwks_loader
        }.delete_if { |_, v| v.nil? }
      )
    )[0]
  rescue Exception => e
    raise BadJwt.new("#{e.class}: #{e.message}")
  end
  (options.required_claims || []).each do |field|
    raise ClaimInvalid.new("Missing required '#{field}' claim.") if !@decoded.key?(field.to_s)
  end
  raise ClaimInvalid.new("Missing required 'iat' claim.") if options.valid_within && !@decoded["iat"]
  if options.valid_within && (Time.now.to_i - @decoded["iat"]).abs > options.valid_within.to_i
    raise ClaimInvalid, "'iat' timestamp claim is too skewed from present"
  end

  @decoded
end

#ec_key(secret) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/omniauth/strategies/jwt.rb', line 73

def ec_key(secret)
  key = if secret.is_a?(OpenSSL::PKey::EC)
    secret
  elsif OpenSSL::PKey.respond_to?(:read)
    OpenSSL::PKey.read(secret)
  else
    OpenSSL::PKey::EC.new(secret)
  end

  ec_public_key(key)
end

#ec_public_key(key) ⇒ Object



85
86
87
88
89
90
91
92
93
94
# File 'lib/omniauth/strategies/jwt.rb', line 85

def ec_public_key(key)
  return key unless key.respond_to?(:private?)
  return key unless key.private?

  public_key = OpenSSL::PKey::EC.new(key.group)
  public_key.public_key = key.public_key
  public_key
rescue OpenSSL::PKey::PKeyError
  key
end

#request_phaseObject



25
26
27
# File 'lib/omniauth/strategies/jwt.rb', line 25

def request_phase
  redirect options.auth_url
end