Class: Rack::JWT::Auth

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

Overview

Authentication middleware

Constant Summary collapse

SUPPORTED_ALGORITHMS =
[
  'none',
  'HS256',
  'HS384',
  'HS512',
  'RS256',
  'RS384',
  'RS512',
  'ES256',
  'ES384',
  'ES512',
  ('ED25519' if defined?(RbNaCl)),
].compact.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.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rack/jwt/auth.rb', line 43

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



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rack/jwt/auth.rb', line 62

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