0
0
Ruby on Railsframework~5 mins

Token-based authentication in Ruby on Rails

Choose your learning style9 modes available
Introduction

Token-based authentication helps your app know who a user is without asking for a password every time. It uses a secret token to keep users logged in safely.

When building an API that needs to identify users without sessions or cookies.
When you want users to stay logged in across different devices or apps.
When you want a simple way to secure requests without managing server sessions.
When building mobile apps that communicate with your Rails backend.
When you want to avoid storing user sessions on the server.
Syntax
Ruby on Rails
class User < ApplicationRecord
  has_secure_token :auth_token
end

# To generate or reset token:
user.regenerate_auth_token

# To authenticate using token:
User.find_by(auth_token: token)

has_secure_token adds methods to generate and manage a unique, secure token attribute. Requires a database column (e.g., add_column :users, :auth_token, :string with add_index :users, :auth_token, unique: true).

You can call regenerate_auth_token to create a new token.

Examples
This adds support for an auth_token attribute to the User model that automatically generates a unique token. Add auth_token column via migration first.
Ruby on Rails
class User < ApplicationRecord
  has_secure_token :auth_token
end
This resets the user's token to a new unique value and prints it.
Ruby on Rails
user = User.find(1)
user.regenerate_auth_token
puts user.auth_token
This shows how to get the token from request headers and find the user by token.
Ruby on Rails
token = request.headers['Authorization']&.split(' ')&.last
user = User.find_by(auth_token: token)
if user
  # user is authenticated
else
  # reject request
end
Sample Program

This example creates a user, generates a token, then finds the user by that token to authenticate. Assumes users table with auth_token column.

Ruby on Rails
class User < ApplicationRecord
  has_secure_token :auth_token
end

# Simulate creating a user and generating a token
user = User.create!
puts "User token: #{user.auth_token}"

# Simulate authenticating with token
token = user.auth_token
found_user = User.find_by(auth_token: token)
if found_user
  puts "Authenticated user ID: #{found_user.id}"
else
  puts "Authentication failed"
end
OutputSuccess
Important Notes

Always keep tokens secret and use HTTPS to protect them during transmission.

Tokens should be long and random to prevent guessing.

Tokens can be revoked by regenerating them if needed.

Summary

Token-based authentication uses a secret token to identify users without passwords each time.

Rails provides has_secure_token to easily add tokens to models.

Tokens help secure APIs and mobile apps without server sessions.