Developer Tools for Random Data Generation // v2.6.1
root@generate-random:~/jwt-tokens/ruby$ _

Generate JWT Tokens in Ruby

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Ruby

What: Generate secure JWT tokens in Ruby using the ruby-jwt gem. Perfect for Rails APIs, Sinatra applications, and Ruby microservices authentication.

Try it: Use our interactive Jwt-tokens generator or integrate this code into your Ruby application.

Generate secure JWT tokens in Ruby using the ruby-jwt gem. Perfect for Rails APIs, Sinatra applications, and Ruby microservices authentication. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Go or use our interactive web generator.

Ruby Code Example

require 'jwt'

# Secret key (store in environment variables)
SECRET_KEY = ENV['JWT_SECRET'] || 'your-256-bit-secret-key'
ISSUER = 'https://yourdomain.com'
AUDIENCE = 'https://yourdomain.com'
ALGORITHM = 'HS256'

def generate_jwt(user_id:, username:, role:)
  payload = {
    user_id: user_id,
    username: username,
    role: role,
    iss: ISSUER,
    aud: AUDIENCE,
    iat: Time.now.to_i,
    exp: Time.now.to_i + 3600  # 1 hour
  }

  JWT.encode(payload, SECRET_KEY, ALGORITHM)
end

def validate_jwt(token)
  begin
    decoded = JWT.decode(
      token,
      SECRET_KEY,
      true,
      {
        algorithm: ALGORITHM,
        iss: ISSUER,
        aud: AUDIENCE,
        verify_iss: true,
        verify_aud: true,
        verify_exp: true
      }
    )
    decoded.first
  rescue JWT::ExpiredSignature
    puts "Token has expired"
    nil
  rescue JWT::DecodeError => e
    puts "Invalid token: #{e.message}"
    nil
  end
end

# Generate token
jwt = generate_jwt(user_id: 123, username: 'john_doe', role: 'admin')
puts jwt
# Output: "eyJhbGciOiJIUzI1NiJ9..."

# Validate token
payload = validate_jwt(jwt)
puts payload['username'] if payload

# Rails middleware example
class JwtAuthenticator
  def self.call(request)
    token = request.headers['Authorization']&.split(' ')&.last
    return nil unless token

    validate_jwt(token)
  end
end

[EXPLANATION]

The ruby-jwt gem is the standard JWT library for Ruby applications. It provides simple encode/decode methods with comprehensive validation options. Use JWT.encode to create tokens and JWT.decode with validation options for verification. The gem supports HS256, RS256, and ES256 algorithms.

Expected Output

eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c

Common Use Cases

  • Rails API authentication
  • Devise JWT integration
  • Sinatra REST APIs
  • Grape API authentication
  • Ruby microservices authorization

Important Notes

  • Install: gem install jwt
  • Use verify_exp: true to validate expiration
  • Consider devise-jwt gem for Rails/Devise integration
  • Store secret keys in Rails credentials or environment variables
  • Use OpenSSL::PKey::RSA for RS256 algorithm

Try Our Interactive Generator

Don't want to write code? Use our free web-based Jwt-tokens generator with instant results.

TRY JWT-TOKENS GENERATOR →