module JWT::Auth::Authentication

Controller methods

Public Instance Methods

current_user() click to toggle source

Current user

# File lib/jwt/auth/authentication.rb, line 14
def current_user
  token&.subject
end
require_token() click to toggle source

Require a token to be present

Apply this filter for API actions that require an access token

@raises JWT::Auth::UnauthorizedError if on token is present

# File lib/jwt/auth/authentication.rb, line 60
def require_token
  raise JWT::Auth::UnauthorizedError if token.nil?
end
set_access_token(user = current_user) click to toggle source

Set API token in the response

# File lib/jwt/auth/authentication.rb, line 67
def set_access_token(user = current_user)
  set_header JWT::Auth::AccessToken.new(:subject => user)
end
set_refresh_token(user = current_user) click to toggle source

Set refresh token in the response

# File lib/jwt/auth/authentication.rb, line 74
def set_refresh_token(user = current_user)
  set_header JWT::Auth::RefreshToken.new(:subject => user)
end
validate_access_token() click to toggle source

Authenticate the user with the token

Apply this filter for API actions that need an access token This filter does not enforce token presence

@raises JWT::Auth::UnauthorizedError if a token is present and it is not a valid access token

# File lib/jwt/auth/authentication.rb, line 37
def validate_access_token
  raise JWT::Auth::UnauthorizedError unless header.nil? || token.is_a?(AccessToken)
end
validate_refresh_token() click to toggle source

Validate a refresh token

Apply this filter for the API token refresh action This filter does not enforce token presence

@raises JWT::Auth::UnauthorizedError if a token is present and it is not a valid refresh token

# File lib/jwt/auth/authentication.rb, line 49
def validate_refresh_token
  raise JWT::Auth::UnauthorizedError unless header.nil? || token.is_a?(RefreshToken)
end
validate_token() click to toggle source

Validate a token (if it's present)

Apply this before_action filter for every API action

@raises JWT::Auth::UnauthorizedError if a token is present and invalid

# File lib/jwt/auth/authentication.rb, line 25
def validate_token
  raise JWT::Auth::UnauthorizedError unless token.nil? || token&.valid?
end

Protected Instance Methods

header() click to toggle source

Extract token from request

# File lib/jwt/auth/authentication.rb, line 87
def header
  header = request.env['HTTP_AUTHORIZATION']
  return nil unless header

  header.scan(/Bearer (.*)$/).flatten.last
end
set_header(token) click to toggle source

Set a token in the response

# File lib/jwt/auth/authentication.rb, line 97
def set_header(token)
  response.headers['Authorization'] = "Bearer #{token.to_jwt}"
end
token() click to toggle source
# File lib/jwt/auth/authentication.rb, line 80
def token
  @token ||= JWT::Auth::Token.from_jwt header
end