README
¶
Security Extension Example
This example demonstrates how to use the security extension for session and cookie management in Forge.
Features
- Session management with in-memory store
- Secure cookie handling with HttpOnly, Secure, and SameSite attributes
- Session middleware for automatic session loading
- Protected routes requiring valid sessions
- Login/logout functionality
- Session data persistence and updates
- Cookie CRUD operations
Running the Example
cd examples/security-example
go run main.go
The server will start on http://localhost:8080.
API Endpoints
Public Endpoints
GET /public
Public endpoint that doesn't require authentication.
curl http://localhost:8080/public
GET /health
Health check endpoint.
curl http://localhost:8080/health
Authentication
POST /login
Create a session by logging in.
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}' \
-c cookies.txt
This will:
- Validate credentials
- Create a new session
- Set a session cookie
- Return session details
Protected Endpoints (Require Session)
GET /api/profile
Get the current user's profile from the session.
curl http://localhost:8080/api/profile \
-b cookies.txt
POST /api/profile
Update the user's profile in the session.
curl -X POST http://localhost:8080/api/profile \
-H "Content-Type: application/json" \
-d '{"bio": "Software Engineer", "location": "San Francisco"}' \
-b cookies.txt
POST /api/logout
Logout and destroy the session.
curl -X POST http://localhost:8080/api/logout \
-b cookies.txt
Cookie Management
GET /cookies/set
Set example cookies (theme and language).
curl http://localhost:8080/cookies/set \
-c cookies.txt
GET /cookies/get
Retrieve all cookies.
curl http://localhost:8080/cookies/get \
-b cookies.txt
GET /cookies/delete
Delete example cookies.
curl http://localhost:8080/cookies/delete \
-b cookies.txt
Testing Flow
- Login and create a session:
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}' \
-c cookies.txt -v
- Access protected profile endpoint:
curl http://localhost:8080/api/profile \
-b cookies.txt
- Update profile data:
curl -X POST http://localhost:8080/api/profile \
-H "Content-Type: application/json" \
-d '{"bio": "DevOps Engineer", "location": "New York"}' \
-b cookies.txt
- Verify the update:
curl http://localhost:8080/api/profile \
-b cookies.txt
- Logout:
curl -X POST http://localhost:8080/api/logout \
-b cookies.txt
- Try to access protected endpoint after logout (should fail):
curl http://localhost:8080/api/profile \
-b cookies.txt
Configuration
The security extension is configured with:
- Session Store: In-memory (for production, use Redis)
- Session Cookie Name:
my_session - Session TTL: 24 hours
- Auto-Renew: Enabled (extends session on each access)
- Cookie Secure: False (set to true in production with HTTPS)
- Cookie HttpOnly: True (prevents XSS attacks)
- Cookie SameSite: Lax (CSRF protection)
Production Considerations
For production deployments:
-
Use Redis for session storage:
security.WithSessionStore("redis"), security.WithRedisAddress("redis://localhost:6379"), -
Enable secure cookies:
security.WithCookieSecure(true), // Requires HTTPS -
Consider session security:
- Enable IP address tracking:
WithSessionTrackIPAddress(true) - Enable user agent tracking:
WithSessionTrackUserAgent(true) - Set appropriate idle timeout
- Implement CSRF protection
- Enable IP address tracking:
-
Use environment variables for secrets:
security.WithRedisPassword(os.Getenv("REDIS_PASSWORD")),
Security Features
Session Security
- Cryptographically secure session ID generation (256-bit random)
- Automatic session expiration
- Session renewal on access (idle timeout)
- Session tracking with IP and user agent (optional)
- Multi-session management per user
Cookie Security
- HttpOnly: Prevents JavaScript access (XSS protection)
- Secure: Only sent over HTTPS (MitM protection)
- SameSite: CSRF protection (Lax, Strict, or None)
- Domain and Path: Scope control
- MaxAge/Expires: Explicit expiration
Extension Architecture
The security extension follows Forge's extension pattern:
- Extension Registration: Registers services with DI container
- Extension Start: Connects to session store
- Extension Stop: Gracefully disconnects
- Health Checks: Verifies session store connectivity
Middleware
The session middleware:
- Automatically loads sessions from cookies
- Stores sessions in request context
- Auto-renews sessions (optional)
- Handles session expiration
- Provides metrics and logging
- Supports path exclusions
Error Handling
The extension provides specific errors:
ErrSessionNotFound: Session doesn't existErrSessionExpired: Session has expiredErrInvalidSession: Session data is corruptedErrCookieNotFound: Cookie doesn't existErrInvalidCookie: Cookie data is invalid
Metrics
The extension tracks:
security.sessions.created: Number of sessions createdsecurity.sessions.retrieved: Number of sessions retrievedsecurity.sessions.updated: Number of sessions updatedsecurity.sessions.deleted: Number of sessions deletedsecurity.sessions.touched: Number of sessions renewedsecurity.sessions.expired: Number of expired sessionssecurity.sessions.active: Current number of active sessionssecurity.sessions.cleaned_up: Number of sessions cleaned up
Further Reading
Documentation
¶
There is no documentation for this package.