Token Authentication for Rails API: Simple Guide
To use
token authentication in a Ruby on Rails API, generate a unique token for each user and require clients to send it in the Authorization header. Verify this token in a controller before allowing access to protected actions.Syntax
Token authentication in Rails API typically involves these parts:
- Token generation: Create a secure token for each user.
- Client sends token: Include the token in the
Authorizationheader of API requests. - Server verifies token: Check the token in a
before_actionfilter to authenticate the user.
ruby
class ApplicationController < ActionController::API before_action :authenticate_user! private def authenticate_user! token = request.headers['Authorization']&.split(' ')&.last unless token && User.find_by(authentication_token: token) render json: { error: 'Unauthorized' }, status: :unauthorized end end end
Example
This example shows a simple Rails API with token authentication. Each user has a unique authentication_token. The API checks this token on every request to protected endpoints.
ruby
class User < ApplicationRecord before_create :generate_authentication_token private def generate_authentication_token self.authentication_token = SecureRandom.hex(20) end end class ApplicationController < ActionController::API before_action :authenticate_user! private def authenticate_user! token = request.headers['Authorization']&.split(' ')&.last @current_user = User.find_by(authentication_token: token) render json: { error: 'Unauthorized' }, status: :unauthorized unless @current_user end end class PostsController < ApplicationController def index render json: { message: "Hello, #{@current_user.email}!" } end end
Output
{"message":"Hello, user@example.com!"}
Common Pitfalls
Common mistakes when using token auth in Rails API include:
- Not securing the token generation, leading to predictable tokens.
- Forgetting to require the token in the
Authorizationheader. - Not handling missing or invalid tokens gracefully.
- Sending tokens in URL parameters instead of headers, which is less secure.
ruby
class ApplicationController < ActionController::API before_action :authenticate_user! private # Wrong: token from params (less secure) def authenticate_user! token = params[:token] @current_user = User.find_by(authentication_token: token) render json: { error: 'Unauthorized' }, status: :unauthorized unless @current_user end end # Correct approach: # Use request.headers['Authorization'] and expect 'Bearer <token>' format
Quick Reference
Tips for token authentication in Rails API:
- Always generate tokens with
SecureRandom.hexor similar secure methods. - Require tokens in the
Authorizationheader asBearer <token>. - Use
before_actionfilters to protect API endpoints. - Return
401 Unauthorizedstatus for invalid or missing tokens. - Keep tokens secret and never expose them in URLs or logs.
Key Takeaways
Use secure, random tokens stored in the user model for authentication.
Require clients to send tokens in the Authorization header as Bearer tokens.
Verify tokens in a before_action filter to protect API endpoints.
Respond with 401 Unauthorized if the token is missing or invalid.
Avoid sending tokens in URL parameters for better security.