Class: Rack::JWT::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/jwt/auth.rb

Overview

Authentication middleware

Constant Summary collapse

SUPPORTED_ALGORITHMS =
%w(none HS256 HS384 HS512 RS256 RS384 RS512 ES256 ES384 ES512).freeze
DEFAULT_ALGORITHM =
'HS256'.freeze
BEARER_TOKEN_REGEX =

The last segment gets dropped for ‘none’ algorithm since there is no signature so both of these patterns are valid. All character chunks are base64url format and periods.

Bearer abc123.abc123.abc123
Bearer abc123.abc123.
%r{
  ^Bearer\s{1}(       # starts with Bearer and a single space
  [a-zA-Z0-9\-\_]+\.  # 1 or more chars followed by a single period
  [a-zA-Z0-9\-\_]+\.  # 1 or more chars followed by a single period
  [a-zA-Z0-9\-\_]*    # 0 or more chars, no trailing chars
  )$
}x

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Auth

Initialization should fail fast with an ArgumentError if any args are invalid.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rack/jwt/auth.rb', line 30

def initialize(app, opts = {})
  @app     = app
  @secret  = opts.fetch(:secret, nil)
  @verify  = opts.fetch(:verify, true)
  @options = opts.fetch(:options, {})
  @exclude = opts.fetch(:exclude, [])

  @secret  = @secret.strip if @secret.is_a?(String)
  @options[:algorithm] = DEFAULT_ALGORITHM if @options[:algorithm].nil?

  check_secret_type!
  check_secret!
  check_secret_and_verify_for_none_alg!
  check_verify_type!
  check_options_type!
  check_valid_algorithm!
  check_exclude_type!
end

Instance Attribute Details

#excludeObject (readonly)

Returns the value of attribute exclude.



10
11
12
# File 'lib/rack/jwt/auth.rb', line 10

def exclude
  @exclude
end

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/rack/jwt/auth.rb', line 9

def options
  @options
end

#secretObject (readonly)

Returns the value of attribute secret.



7
8
9
# File 'lib/rack/jwt/auth.rb', line 7

def secret
  @secret
end

#verifyObject (readonly)

Returns the value of attribute verify.



8
9
10
# File 'lib/rack/jwt/auth.rb', line 8

def verify
  @verify
end

Instance Method Details

#call(env) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rack/jwt/auth.rb', line 49

def call(env)
  if path_matches_excluded_path?(env)
    @app.call(env)
  elsif missing_auth_header?(env)
    return_error('Missing Authorization header')
  elsif invalid_auth_header?(env)
    return_error('Invalid Authorization header format')
  else
    verify_token(env)
  end
end