Module: Cloudtasker::Authenticator

Defined in:
lib/cloudtasker/authenticator.rb

Overview

Manage token generation and verification

Constant Summary collapse

JWT_ALG =

Algorithm used to sign the verification token

'HS256'

Class Method Summary collapse

Class Method Details

.bearer_tokenString

The Authorization header content

Returns:

  • (String)

    The Bearer authorization header



37
38
39
# File 'lib/cloudtasker/authenticator.rb', line 37

def bearer_token
  "Bearer #{verification_token}"
end

.configCloudtasker::Config

Return the cloudtasker configuration. See Cloudtasker#configure.

Returns:



18
19
20
# File 'lib/cloudtasker/authenticator.rb', line 18

def config
  Cloudtasker.config
end

.sign_payload(payload) ⇒ String

Generate a signature for a payload

Parameters:

  • payload (String)

    The JSON payload

Returns:

  • (String)

    The HMAC signature



73
74
75
# File 'lib/cloudtasker/authenticator.rb', line 73

def sign_payload(payload)
  OpenSSL::HMAC.hexdigest('sha256', config.secret, payload)
end

.verification_tokenString

A Json Web Token (JWT) which will be used by the processor to authenticate the job.

Returns:

  • (String)

    The jwt token



28
29
30
# File 'lib/cloudtasker/authenticator.rb', line 28

def verification_token
  JWT.encode({ iat: Time.now.to_i }, config.secret, JWT_ALG)
end

.verify(bearer_token) ⇒ Boolean

Verify a bearer token (jwt token)

Parameters:

  • bearer_token (String)

    The token to verify.

Returns:

  • (Boolean)

    Return true if the token is valid



48
49
50
51
52
# File 'lib/cloudtasker/authenticator.rb', line 48

def verify(bearer_token)
  JWT.decode(bearer_token, config.secret)
rescue JWT::VerificationError, JWT::DecodeError
  false
end

.verify!(bearer_token) ⇒ Boolean

Verify a bearer token and raise a ‘Cloudtasker::AuthenticationError` if the token is invalid.

Parameters:

  • bearer_token (String)

    The token to verify.

Returns:

  • (Boolean)

    Return true if the token is valid



62
63
64
# File 'lib/cloudtasker/authenticator.rb', line 62

def verify!(bearer_token)
  verify(bearer_token) || raise(AuthenticationError)
end

.verify_signature!(signature, payload) ⇒ Boolean

Verify that a signature matches the payload and raise a ‘Cloudtasker::AuthenticationError` if the signature is invalid.

Parameters:

  • signature (String)

    The tested signature

  • payload (String)

    The JSON payload

Returns:

  • (Boolean)

    Return true if the signature is valid



86
87
88
# File 'lib/cloudtasker/authenticator.rb', line 86

def verify_signature!(signature, payload)
  ActiveSupport::SecurityUtils.secure_compare(signature, sign_payload(payload)) || raise(AuthenticationError)
end