Authentication Generator
Generate a complete, production-ready authentication system with support for JWT, sessions, OAuth, and advanced security features including RBAC (Role-Based Access Control).
Synopsis
azu generate auth [options]Description
The auth generator creates a comprehensive authentication system for your Azu application, including user models, authentication endpoints, security middleware, and database migrations. It supports multiple authentication strategies and can be configured with advanced features like role-based access control, CSRF protection, and OAuth integration.
Features
Core Authentication
✅ User Registration: Secure user signup with email verification
✅ Login/Logout: Session or token-based authentication
✅ Password Management: Secure password hashing with BCrypt (cost: 14)
✅ Password Reset: Email-based password recovery
✅ Email Confirmation: Account verification workflow
✅ Account Locking: Automatic lockout after failed attempts
Security Features
🔐 BCrypt Password Hashing: Industry-standard with high cost factor
🎫 JWT Support: Secure token generation with refresh tokens
🛡️ CSRF Protection: Cross-site request forgery prevention
🔒 Security Headers: Comprehensive HTTP security headers
🚫 Rate Limiting: Protection against brute force attacks
🔑 Two-Factor Authentication: Optional 2FA support (infrastructure ready)
Advanced Features
👥 RBAC: Complete role-based access control system
🌐 OAuth Integration: Google and GitHub authentication
⏰ Token Expiration: Configurable access and refresh tokens
📊 Audit Trail: Track login attempts and security events
🎯 Permission System: Granular permission management
Usage
Basic Usage
Generate authentication with default settings (Authly strategy with RBAC):
This creates a complete authentication system with:
User model with security features
Authentication endpoints (register, login, logout)
JWT token management
RBAC tables and structure
Security middleware
Strategy-Specific Generation
Authly (Recommended)
Full-featured OAuth2 server with JWT and RBAC:
Features:
OAuth2 server capabilities
JWT access and refresh tokens
RBAC and permissions
OAuth provider integration
Comprehensive security
JWT Only
Simple JWT-based authentication:
Features:
JWT access tokens
Refresh token support
User model with basic auth
Login/register endpoints
Session-Based
Traditional session authentication using the Session shard:
Features:
Server-side encrypted sessions: Secure cookie-based authentication
Strongly-typed session data: Type-safe session payload with Crystal structs
Multiple storage backends: Memory (default), Redis, or Database
Auto-expiration: Configurable timeout (default: 1 hour for CSRF, 24 hours without)
Session lifecycle callbacks: on_started, on_deleted events
Automatic integration: Generates session config, middleware, and helper methods
Dependency management: Automatically adds session shard to shard.yml
What gets generated:
Session configuration file (
src/config/session.cr)Session HTTP handler middleware (
src/middleware/session_handler.cr)Strongly-typed session struct (
Sessions::AccountSessionorSessions::UserSession)Session helper method (
YourApp.session)Updated endpoints to use session storage
Environment variable template for SESSION_SECRET
OAuth
External OAuth provider authentication:
Features:
Google OAuth
GitHub OAuth
Extensible provider support
Advanced Options
Options
--strategy <type>
string
authly
Authentication strategy: authly, jwt, session, oauth
--user-model <name>
string
User
Custom name for the user model class (e.g., Account)
--enable-rbac
flag
true
Enable role-based access control
--no-rbac
flag
Disable RBAC features
--enable-csrf
flag
true
Enable CSRF protection
--no-csrf
flag
Disable CSRF protection
--oauth-providers <list>
comma-separated
google,github
OAuth providers to enable
--force
flag
false
Overwrite existing files
Custom User Model
The --user-model option allows you to use a custom name for your user model instead of the default User. This is useful when:
You need to avoid naming conflicts
Your domain uses different terminology (Account, Member, etc.)
You're integrating with existing systems
Example:
This generates:
Model class:
Account(notUser)Table:
accounts(notusers)RBAC tables:
account_roles(notuser_roles)All migrations and endpoints use the custom model name
Generated Files
Directory Structure
The generator creates different files based on your chosen strategy:
Note: Migrations are generated in src/db/migrations/ with unique incremental timestamps to avoid conflicts.
File Descriptions
User Model (src/models/user.cr)
src/models/user.cr)Complete user model with CQL ORM (name depends on --user-model option):
Note: The model name and table name automatically adjust based on the --user-model option.
Authentication Endpoints (src/endpoints/auth/*_endpoint.cr)
src/endpoints/auth/*_endpoint.cr)RESTful authentication API (per action files):
POST /auth/register- User registration (register_endpoint.cr)POST /auth/login- User login (login_endpoint.cr)POST /auth/logout- User logout (logout_endpoint.cr)POST /auth/refresh- Refresh access token (refresh_endpoint.cr, jwt/authly)POST /auth/change-password- Change authenticated user password (change_password_endpoint.cr)GET /auth/me- Current user (me_endpoint.cr)GET /auth/permissions- RBAC permissions (permissions_endpoint.cr)GET /auth/oauth/:providerandGET /auth/oauth/:provider/callback(authly)
CSRF Protection Middleware (src/middleware/csrf_protection.cr)
src/middleware/csrf_protection.cr)Protects against cross-site request forgery:
Security Headers Middleware (src/middleware/security_headers.cr)
src/middleware/security_headers.cr)Comprehensive HTTP security headers:
Database Schema
Users Table
Core user authentication table:
id
Int64
Primary key
email
String
Unique email address
password_hash
String
BCrypt password hash
name
String
User's full name
role
String
User role (default: "user")
confirmed_at
Time?
Email confirmation timestamp
locked_at
Time?
Account lock timestamp
failed_login_attempts
Int32
Failed login counter
last_login_at
Time?
Last successful login
password_changed_at
Time?
Password change timestamp
two_factor_enabled
Bool
2FA enabled flag
two_factor_secret
String?
2FA secret key
recovery_codes
String?
Backup recovery codes
created_at
Time
Creation timestamp
updated_at
Time
Last update timestamp
RBAC Tables (when --enable-rbac)
--enable-rbac)Roles Table
id
Int64
Primary key
name
String
Role name (unique)
description
String
Role description
permissions
String
JSON permissions array
created_at
Time
Creation timestamp
updated_at
Time
Last update timestamp
Permissions Table
id
Int64
Primary key
name
String
Permission name (unique)
description
String
Permission description
resource
String
Resource type
action
String
Action type
created_at
Time
Creation timestamp
User_Roles Junction Table
id
Int64
Primary key
user_id
Int64
Foreign key to users
role_id
Int64
Foreign key to roles
assigned_at
Time
Assignment timestamp
assigned_by
Int64?
Assigning user ID
Role_Permissions Junction Table
id
Int64
Primary key
role_id
Int64
Foreign key to roles
permission_id
Int64
Foreign key to permissions
created_at
Time
Creation timestamp
OAuth Tables (when --strategy authly)
--strategy authly)OAuth_Applications Table
id
Int64
Primary key
name
String
Application name
client_id
String
Unique client ID
client_secret
String
Client secret
redirect_uri
String
OAuth redirect URI
scopes
String
Allowed scopes
confidential
Bool
Confidential flag
created_at
Time
Creation timestamp
updated_at
Time
Last update timestamp
OAuth_Access_Tokens Table
id
Int64
Primary key
application_id
Int64
Foreign key to applications
resource_owner_id
Int64
User ID
token
String
Access token (unique)
refresh_token
String?
Refresh token (unique)
expires_in
Int32
Token lifetime (seconds)
scopes
String
Granted scopes
created_at
Time
Creation timestamp
revoked_at
Time?
Revocation timestamp
Configuration
Environment Variables
Add to .env:
Authly Configuration (src/config/authly.cr)
src/config/authly.cr)Usage Examples
User Registration
User Login
Token Refresh
Password Reset
Using Authentication in Endpoints
RBAC Usage
Seeding Roles and Permissions
Checking Permissions
Security Best Practices
1. Strong Secrets
Generate cryptographically secure secrets:
2. Password Requirements
Enforce strong passwords in validation:
3. Rate Limiting
Implement rate limiting on auth endpoints:
4. Secure Token Storage
Client-side token storage recommendations:
Web: Use httpOnly, secure cookies for refresh tokens
SPA: Store access tokens in memory, refresh tokens in httpOnly cookies
Mobile: Use secure keychain/keystore
5. Token Rotation
Rotate refresh tokens on use:
Dependencies
Add to shard.yml:
Migration and Setup
After generation:
Testing
Example authentication tests:
Troubleshooting
JWT Token Issues
Problem: "JWT_SECRET environment variable not set"
Solution:
BCrypt Cost Too High
Problem: Login is slow
Solution: Adjust BCrypt cost (default: 14):
CSRF Token Mismatch
Problem: "CSRF token validation failed"
Solution:
Ensure CSRF token is included in requests
Check token matches session value
Verify middleware order
Account Lockout
Problem: Can't login after failed attempts
Solution:
Related Documentation
See Also
azu session:setup- Configure session storageazu generate model- Generate modelsazu db:migrate- Run migrations
Last updated