DevToolsForYou

JWT Encoder and Decoder in Ruby — Code Examples

JWT Encoder and Decoder in RubyUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

The jwt gem is the standard Ruby JWT library. Use JWT.encode to sign and JWT.decode with verify=true to validate.

Ruby
# gem install jwt
require 'jwt'

secret = "my-secret-key"
payload = {
  user_id: 42,
  name: "Alice",
  role: "admin",
  exp: Time.now.to_i + 3600
}

# Sign (encode)
token = JWT.encode(payload, secret, "HS256")
puts token
# eyJhbGciOiJIUzI1NiJ9...

# Verify and decode
begin
  decoded_payload, header = JWT.decode(token, secret, true, { algorithm: "HS256" })
  puts decoded_payload["name"]    # Alice
  puts decoded_payload["user_id"] # 42
  puts header["alg"]              # HS256
rescue JWT::ExpiredSignature
  puts "Token has expired"
rescue JWT::DecodeError => e
  puts "Invalid token: #{e.message}"
end

# Decode without verifying (inspect only — do not use for auth)
payload_only, _header = JWT.decode(token, nil, false)
puts payload_only["name"] # Alice
Notes & gotchas
  • Always pass verify=true (the third argument) in production — false disables signature verification entirely.
  • exp is automatically checked when verify=true; the value must be a Unix timestamp integer.
  • For RS256, pass an OpenSSL::PKey::RSA private key to encode and the public key to decode.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages