Authentication

suggest change

Authentication verifies the identity of a client or user before granting access to protected application resources. In Ruby, authentication is commonly implemented using secure password hashing (bcrypt), HTTP Basic authentication middleware (Rack::Auth::Basic), JSON Web Tokens (jwt), and cryptographically secure random tokens.


1. Password Hashing with BCrypt

Never store passwords in plain text or with standard hash algorithms like MD5 or SHA-256 (which are vulnerable to GPU-based rainbow table attacks). The standard solution in Ruby is BCrypt, an adaptive key derivation function based on the Blowfish cipher.

Install the bcrypt gem:

gem install bcrypt

Hashing and Verifying Passwords

require 'bcrypt'

# 1. Hashing a password upon registration
raw_password = 'correct horse battery staple'
# Cost factor determines computational work (default is 12)
hashed_password = BCrypt::Password.create(raw_password, cost: 12)

puts hashed_password
# Example output: $2a$12$e8Y7z7r3W4X5u8g...

# 2. Authenticating a user upon login
input_password = 'user_submitted_password'
stored_hash = BCrypt::Password.new(hashed_password)

if stored_hash == input_password
  puts "Authentication successful!"
else
  puts "Invalid credentials."
end

The BCrypt::Password#== operator automatically extracts the salt and cost from the stored hash string and performs a secure comparison.


2. HTTP Basic Authentication with Rack

Rack provides built-in HTTP Basic authentication via Rack::Auth::Basic. Because Hanami, Sinatra, and Rails are built on Rack, this middleware can protect whole applications or specific endpoints:

require 'rack'

app = Rack::Builder.new do
  use Rack::Auth::Basic, "Admin Restricted Area" do |username, password|
    # Timing-safe comparison against credentials
    Rack::Utils.secure_compare(username, 'admin') &
      Rack::Utils.secure_compare(password, 'supersecret')
  end

  run ->(env) {
    [200, { 'content-type' => 'text/plain' }, ["Welcome, #{env['REMOTE_USER']}!"]]
  }
end

If the client fails to provide valid credentials in the Authorization: Basic <base64> header, Rack returns an HTTP 401 Unauthorized response with the WWW-Authenticate header.


3. Token-Based Authentication with JWT

Stateless APIs often use JSON Web Tokens (JWT) to authenticate requests without keeping server-side session state.

Install the jwt gem:

gem install jwt

Encoding and Decoding Tokens

require 'jwt'
require 'time'

HMAC_SECRET = ENV.fetch('JWT_SECRET', 'a-very-long-and-secure-secret-key-32-bytes')

# Issue a token with expiration and user ID
def issue_token(user_id)
  payload = {
    user_id: user_id,
    exp: Time.now.to_i + 3600, # Expires in 1 hour
    iat: Time.now.to_i          # Issued at
  }

  JWT.encode(payload, HMAC_SECRET, 'HS256')
end

# Verify and decode token
def authenticate_token(token)
  decoded, _header = JWT.decode(
    token,
    HMAC_SECRET,
    true, # Verify signature
    { algorithm: 'HS256' }
  )
  decoded # Returns hash payload with string keys
rescue JWT::ExpiredSignature
  { error: 'Token has expired' }
rescue JWT::DecodeError => e
  { error: "Invalid token: #{e.message}" }
end

token = issue_token(42)
puts "Token: #{token}"

result = authenticate_token(token)
puts "Authenticated user ID: #{result['user_id']}"

4. Constant-Time Comparison to Prevent Timing Attacks

Standard string equality (==) terminates early on the first mismatched byte. An attacker can measure request response times down to nanoseconds to guess passwords or authentication tokens character by character.

To prevent timing side-channel attacks, always use constant-time comparison:

require 'openssl'
require 'securerandom'

# Generating cryptographically secure API keys / reset tokens
api_key = SecureRandom.hex(32) # 64-character hexadecimal string
session_token = SecureRandom.urlsafe_base64(32)

# Constant-time comparison
user_supplied_token = "some_incoming_token"
actual_token = "some_stored_secret"

# OpenSSL constant-time comparison
is_valid = OpenSSL.fixed_length_secure_compare(
  OpenSSL::Digest::SHA256.digest(user_supplied_token),
  OpenSSL::Digest::SHA256.digest(actual_token)
)

5. Custom Rack Bearer Token Middleware

Here is how to implement a clean Bearer Token authentication middleware in Ruby:

require 'jwt'
require 'json'

class BearerAuthMiddleware
  def initialize(app, secret:)
    @app = app
    @secret = secret
  end

  def call(env)
    auth_header = env['HTTP_AUTHORIZATION']

    if auth_header && auth_header.start_with?('Bearer ')
      token = auth_header.split(' ', 2).last
      begin
        payload, = JWT.decode(token, @secret, true, { algorithm: 'HS256' })
        env['app.current_user_id'] = payload['user_id']
        return @app.call(env)
      rescue JWT::DecodeError
        return unauthorized_response('Invalid or expired authentication token')
      end
    end

    unauthorized_response('Missing Authorization Bearer header')
  end

  private

  def unauthorized_response(message)
    body = { error: 'Unauthorized', message: message }.to_json
    [
      401,
      { 'content-type' => 'application/json', 'www-authenticate' => 'Bearer' },
      [body]
    ]
  end
end

Security Best Practices

  1. Always Use HTTPS: Authentication credentials (headers, cookies, tokens) sent over unencrypted HTTP can be intercepted over the network.
  2. Never Hardcode Secrets: Store JWT secret keys and database credentials in environment variables (ENV['SECRET_KEY_BASE']).
  3. Use Timing-Safe Comparisons: Use Rack::Utils.secure_compare or OpenSSL.fixed_length_secure_compare when evaluating sensitive strings.
  4. Implement Rate Limiting: Protect login and token endpoints with rack-attack or Redis-backed rate limiting to defend against brute-force attacks.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents