Module: JWTKeeper::Controller

Extended by:
ActiveSupport::Concern
Defined in:
lib/jwt_keeper/controller.rb

Instance Method Summary collapse

Instance Method Details

#authenticated(token) ⇒ void

This method returns an undefined value.

The default action for accepting authenticated connections. You can override this method in your controllers



57
58
# File 'lib/jwt_keeper/controller.rb', line 57

def authenticated(token)
end

#clear_authentication_tokenvoid

This method returns an undefined value.

delets the authentication token



48
49
50
51
52
# File 'lib/jwt_keeper/controller.rb', line 48

def clear_authentication_token
  response.headers['Authorization'] = nil
  defined?(cookies) && cookies.delete('jwt_keeper')
  @authentication_token = nil
end

#read_authentication_tokenToken

Decodes and returns the token

Returns:

  • (Token)

    the token read from request



27
28
29
30
31
32
33
34
# File 'lib/jwt_keeper/controller.rb', line 27

def read_authentication_token
  return nil unless request.headers['Authorization']
  @authentication_token ||=
    JWTKeeper::Token.find(
      request.headers['Authorization'].split.last,
      cookie_secret: defined?(cookies) && cookies.signed['jwt_keeper']
    )
end

#regenerate_claims(old_token) ⇒ void

This method returns an undefined value.

Invoked by the require_authentication method as part of the automatic rotation process. The application should override this method to include the necessary claims.



64
65
# File 'lib/jwt_keeper/controller.rb', line 64

def regenerate_claims(old_token)
end

#require_authenticationvoid

This method returns an undefined value.

Available to be used as a before_action by the application’s controllers. This is the main logical section for decoding, and automatically rotating tokens



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jwt_keeper/controller.rb', line 8

def require_authentication
  token = read_authentication_token

  if token.nil?
    clear_authentication_token
    raise JWTKeeper::NotAuthenticatedError
  end

  if token.version_mismatch? || token.pending?
    new_claims = regenerate_claims(token)
    token.rotate(new_claims)
  end

  write_authentication_token(token)
  authenticated(token)
end

#write_authentication_token(token) ⇒ Token

Encodes and writes the token

Parameters:

  • token (Token)

    The token to be written

Returns:

  • (Token)

    the token written to response



39
40
41
42
43
44
# File 'lib/jwt_keeper/controller.rb', line 39

def write_authentication_token(token)
  return clear_authentication_token if token.nil?
  response.headers['Authorization'] = "Bearer #{token.to_jwt}"
  defined?(cookies) && cookies.signed['jwt_keeper'] = token.to_cookie
  @authentication_token = token
end