Module: JwtAuthenticable::Auth

Includes:
Exceptions, Responses
Defined in:
lib/jwt_authenticable/auth.rb

Overview

Module that adds jwt authentication methods to the client

Instance Method Summary collapse

Methods included from Responses

#accepted, #access_denied, #created, #destroyed, #no_content, #not_found, #payload_too_large, #render_page, #render_resource, #render_success_resource, #unauthorized, #unprocessable_entity, #validation_error

Instance Method Details

#algorithmObject



57
58
59
# File 'lib/jwt_authenticable/auth.rb', line 57

def algorithm
  supported_algos.find { |algo| algo == JwtAuthenticable.config.algorithm } || 'HS256'
end

#authenticate_user!Object

Authenticates a user.

Raises:

  • MissingAuthScope if the jwt does not have the right scope



14
15
16
17
18
19
# File 'lib/jwt_authenticable/auth.rb', line 14

def authenticate_user!
  validate_jwt_token! token: authorization_token!
rescue MissingAuth, MissingAuthScope, InvalidAuthScheme, TwoFANotEnabledError, JWT::VerificationError,
       JWT::ExpiredSignature => e
  unauthorized(e.message)
end

#authorization_token!String

Note:

For now we only support Bearer schema with JWT

Extracts the authorization token from the Authorization header

Returns:

  • (String)

    the JWT token string

Raises:



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jwt_authenticable/auth.rb', line 45

def authorization_token!
  raise InvalidIncluder unless defined? request

  auth_token = request.headers['Authorization']
  auth_token ||= request.cookies['bearer_token']

  raise MissingAuth if auth_token.nil? || auth_token == ''
  raise InvalidAuthScheme if auth_token[0..6] != 'Bearer '

  auth_token[7..]
end

#supported_algosObject



61
62
63
# File 'lib/jwt_authenticable/auth.rb', line 61

def supported_algos
  SUPPORTED_ALGOS.flat_map { |algo_class| algo_class.const_get(:SUPPORTED) }
end

#validate_jwt_token!(token:) ⇒ Hash

Validate that the JWT token signature and the following claims are valid:

- exp
- scope

Parameters:

  • token (String)

    JWT token string (just the token, with the header, payload and signature separated by ‘.’)

  • is_researcher (Boolean)

    Whether to validate the token as a researcher’s or a participant’s

Returns:

  • (Hash)

    the JWT payload

Raises:

  • AuthorizationError if the user is trying to login with the incorrect rights.



30
31
32
33
34
35
36
37
38
# File 'lib/jwt_authenticable/auth.rb', line 30

def validate_jwt_token!(token:)
  # NOTE: it is still safe if JWT_SECRET_KEY is not set. The method will trigger a JWT exception
  payload = JWT.decode(token, JwtAuthenticable.config.jwt_secret_key, true,
                       { algorithm: algorithm }).first

  raise TwoFANotEnabledError if JwtAuthenticable.config.enforce_2fa && !payload['2fa']

  payload
end