A simple, serverless and stateless authentication gateway for client applications that need to interact with third-party APIs while keeping authentication tokens server-side.
- 🔐 Secure Token Management: Uses AWS Parameter Store for encrypted token storage
- 🌐 Domain Restriction: CORS and origin validation for security
- 📊 Cost-Optimized Monitoring: CloudWatch with configurable retention policies
- 🔧 Extensible Configuration: JSON-based routing and policy system
- Project Background
- Quick Start
- Request Flow
- Configuration
- API Endpoints
- Authentication
- Error Responses
- Path Matching
- CORS Support
- Monitoring and Logging
- Security Considerations
- Troubleshooting
- Important Notice
- Contributing
This project was built over weekends to solve a specific problem: the need for a simple, serverless authentication gateway that could securely proxy requests to third-party APIs while keeping authentication tokens server-side. It's designed to be lightweight, cost-effective, and easy to deploy.
While functional and tested, it's important to understand that this is a personal project that may not have the same level of enterprise-grade features, support, or security hardening as commercial solutions.
- AWS CLI configured
- Python 3.12+
- Terraform 1.0+
- GNU Make 4.3+ (optional)
# Clone the repository
git clone <repository-url>
cd authru
# Install dependencies
make install
# Run tests
make test
# Bootstrap Terraform
make bootstrap
# Deploy to AWS
make deploy- Client Request: Client sends request to API Gateway endpoint
- CORS Validation: Origin is validated against allowed domains
- Route Matching: Request path is matched against configured routes
- Authentication: If no auth header exists, credentials are retrieved from Parameter Store
- Request Forwarding: Request is forwarded to target API with authentication
- Response Passthrough: Response is returned to client with original status/headers
Routes are defined in config/routes.json:
{
"routes": [
{
"name": "my-api",
"pathPattern": "/api/v1/*",
"targetBaseUrl": "https://api.example.com",
"authentication": {
"scheme": "Bearer",
"parameterName": "/authru/tokens/my-api"
},
"policies": {
"timeout": 30000,
"retries": 3
}
}
]
}- name: Unique identifier for the route
- pathPattern: URL pattern to match (supports
*wildcard) - targetBaseUrl: Base URL of the target API
- authentication.scheme: Authentication scheme (
Bearer,BasicandApiKeysupported) - authentication.parameterName: AWS Parameter Store parameter name
- policies.timeout: Request timeout in milliseconds (optional)
- policies.retries: Number of retry attempts (optional)
{
"security": {
"allowedOrigins": [
"https://yourdomain.com",
"https://app.yourdomain.com",
"*.yourdomain.com"
],
"corsEnabled": true,
"allowCredentials": false
}
}- allowedOrigins: List of allowed origins for CORS
- corsEnabled: Enable/disable CORS validation
- allowCredentials: Allow credentials in CORS requests
{
"monitoring": {
"logRetentionDays": 7,
"logLevel": "INFO",
"enableMetrics": true,
"enableTracing": false
}
}All HTTP Methods: /{proxy+}
Forwards requests to configured third-party APIs based on path matching.
- Origin: Required for CORS validation
- Authorization: Optional - if present, will be passed through; if missing, will be added
Returns the exact response from the target API, including:
- Status code
- Headers (with CORS headers added)
- Body content
# Client request
curl -X GET "https://your-api-gateway-url/api/v1/users?limit=10" \
-H "Origin: https://yourdomain.com" \
-H "Accept: application/json"
# Forwarded to target API as:
curl -X GET "https://api.example.com/v1/users?limit=10" \
-H "Authorization: Bearer <base64-encoded-credentials>" \
-H "Accept: application/json"OPTIONS: /{proxy+}
Handles CORS preflight requests.
Access-Control-Allow-Origin: Matched origin or*Access-Control-Allow-Methods: Allowed HTTP methodsAccess-Control-Allow-Headers: Allowed request headersAccess-Control-Max-Age: Cache duration for preflight
All credentials are stored in AWS Parameter Store and processed according to the following flow:
- Retrieve credentials from Parameter Store
- Base64 encode
credentials - Add as
Authorization: <Scheme> <encoded-credentials>header
# Store credentials securely
aws ssm put-parameter \
--name "/authru/tokens/my-api" \
--value "your-username:your-password" \
--type "SecureString" \
--region eu-west-1You can also add parameters through Terraform by configuring them in terraform/deployment/parameter_store.tf. But this might bring some security risks (e.g. pushing secrets to version control.).
Here is an example:
resource "aws_ssm_parameter" "my_api_token" {
name = "/authru/tokens/my-api"
description = "API credentials for my-api"
type = "SecureString"
value = "your-username:your-password"
tags = merge(local.common_tags, {
Name = "authru-my-api-token"
})
lifecycle {
ignore_changes = [value] # Don't overwrite if manually updated
}
}To enable this example parameter creatino, set create_example_parameter = true in your terraform.tfvars file.
All errors return JSON with consistent format:
{
"error": "Error message",
"statusCode": 400
}- 403: Origin not allowed (CORS violation)
- 404: No matching route found
- 500: Configuration or authentication error
- 502: Target API error or timeout
Routes use glob-style patterns:
/api/v1/*matches/api/v1/users,/api/v1/orders/123/webhooks/*matches/webhooks/stripe,/webhooks/github- Exact matches:
/healthonly matches/health
The matched prefix is removed when forwarding:
- Route pattern:
/api/v1/* - Request path:
/api/v1/users/123 - Forwarded path:
/users/123
Configure allowed origins in the security section:
{
"allowedOrigins": [
"https://yourdomain.com", // Exact match
"*.yourdomain.com", // Subdomain wildcard
"*" // Allow all (not recommended)
]
}The proxy automatically handles OPTIONS requests for CORS preflight:
- Validates origin against allowed list
- Returns appropriate CORS headers
- Caches preflight response for 24 hours
Structured JSON logs include:
{
"timestamp": "2024-01-01T12:00:00Z",
"level": "INFO",
"logger": "src.handlers.proxy_handler",
"message": "Forwarding GET request to https://api.example.com/users",
"route_name": "my-api",
"method": "GET",
"target_url": "https://api.example.com/users"
}Available CloudWatch metrics:
- Lambda invocations, errors, duration
- API Gateway requests, latency, errors
- Custom metrics for route-specific monitoring
- Log retention: 7 days (configurable)
- Log level: INFO (configurable)
- Structured logging for efficient querying
- Parameter Store caching for reduced API calls
- Least Privilege: Grant minimal IAM permissions
- Secure Parameters: Use SecureString type in Parameter Store
- Origin Validation: Always configure allowed origins
- Regular Rotation: Rotate API credentials regularly
- Monitoring: Monitor for unusual access patterns
Lambda function needs:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:*:*:parameter/authru/*"
}
]
}-
403 Origin not allowed
- Check
allowedOriginsconfiguration - Verify Origin header in request
- Check
-
404 No matching route
- Check route
pathPatternconfiguration - Verify request path format
- Check route
-
500 Authentication error
- Verify Parameter Store parameter exists
- Check IAM permissions for Lambda
- Validate credential format (
username:password)
-
502 Bad Gateway
- Check target API availability
- Verify
targetBaseUrlconfiguration - Check timeout settings
Enable debug logging:
# Set environment variable
LOG_LEVEL=DEBUG
# Or update Lambda configuration
aws lambda update-function-configuration \
--function-name authru \
--environment Variables='{LOG_LEVEL=DEBUG}'This project is in early development stage and should be used with caution in production environments.
Before deploying to production, please consider:
- Security Review: Conduct a thorough security audit of the authentication flow and CORS implementation
- Load Testing: Test the system under expected production load
- Monitoring Setup: Ensure comprehensive monitoring and alerting is in place
- Backup Strategy: Implement proper backup and disaster recovery procedures
- Compliance: Verify compliance with your organization's security policies and regulatory requirements
Any kind of contributions are welcome! This project was built to solve a specific need, but there's always room for improvement.
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and ensure tests pass
- Commit your changes:
git commit -m 'Add some amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
- Follow Python PEP 8 guidelines
- Use type hints where appropriate
- Add docstrings for public functions
- Include tests for new functionality
- Update documentation for new features
When reporting issues, please include:
- Environment details: Python version, AWS region, deployment method
- Configuration: Relevant parts of your configuration files (sanitized)
- Error logs: Full error messages and stack traces
- Steps to reproduce: Clear steps to reproduce the issue
- Expected vs actual behavior: What you expected vs what happened
If you discover a security vulnerability, please do not open a public issue. Instead, please contact the maintainer directly with details about the vulnerability.