Authentication
Complete authentication system with OAuth, JWT tokens, and user management
All authentication routes are prefixed with /auth
and tagged as auth
in
the API documentation.
Features
OAuth Integration
Support for multiple OAuth providers (Google, GitHub, etc.)
JWT Tokens
Secure access and refresh token implementation
Email Verification
Email verification system for new user accounts
Password Reset
Secure password reset via email tokens
OAuth Authentication
Initiate OAuth Login
GET /auth/oauth/{provider}
Start the OAuth login process for a supported provider.
Parameters:
provider
(path): OAuth provider name (e.g., 'google', 'github')
Response: Redirects to the OAuth provider's authorization page.
Returns 404 if provider is not supported or 503 if provider is not configured.
OAuth Callback
GET /auth/oauth/callback/{provider}
Handle OAuth callback and issue JWT tokens.
Parameters:
provider
(path): OAuth provider name
Response: Redirects to frontend with access and refresh tokens as query parameters.
Redirect to: {FRONTEND_URL}/auth?access_token={token}&refresh_token={token}
{
"detail": "Could not validate credentials"
}
User Registration & Verification
Create User
POST /auth/create-user
Register a new user account.
Request Body:
{
"username": "string",
"email": "string",
"password": "string"
}
Response:
{
"message": "User created. Check your email to verify."
}
Users must verify their email before they can log in.
Verify Email
GET /auth/verify-email
Verify user's email address using the verification token.
Query Parameters:
token
(required): Email verification token
Response: Redirects to frontend login page with status message.
Redirect to: {FRONTEND_URL}/login?detail=email_verified
Redirect to: {FRONTEND_URL}/login?detail=already_verified
Authentication & Tokens
Login
POST /auth/token
Authenticate user and return JWT tokens.
Request Body (Form Data):
username: string
password: string
Response:
{
"access_token": "string",
"refresh_token": "string",
"token_type": "bearer"
}
Returns 401 if credentials are invalid or email is not verified.
Refresh Token
POST /auth/refresh
Refresh both access and refresh tokens.
Request Body:
{
"refresh_token": "string"
}
Response:
{
"access_token": "string",
"refresh_token": "string",
"token_type": "bearer"
}
Both tokens are refreshed to maintain security. Store the new refresh token.
Get Current User
GET /auth/get-user
Get information about the currently authenticated user.
Headers:
Authorization: Bearer {access_token}
Response:
{
"id": "integer",
"username": "string",
"email": "string",
"is_verified": "boolean",
"created_at": "datetime"
// ... other user fields
}
User Profile Management
Update User Profile
PATCH /auth/update-user
Update user profile information with field restrictions.
Headers:
Authorization: Bearer {access_token}
Request Body:
{
"username": "string",
"first_name": "string",
"last_name": "string"
// ... other updatable fields
}
Restricted Fields: The following fields cannot be updated:
id
created_at
is_admin
hashed_password
google_sub
email
Attempting to update restricted fields will result in a 400 error.
Password Reset
Request Password Reset
POST /auth/request-password-reset
Send a password reset link to the user's email.
Request Body:
{
"email": "string"
}
Response:
{
"detail": "If the email exists, a reset link has been sent."
}
The response is the same whether the email exists or not, preventing email enumeration attacks.
Reset Password
POST /auth/reset-password
Reset the user's password using a valid reset token.
Request Body:
{
"token": "string",
"new_password": "string"
}
Response:
{
"detail": "Password reset successful"
}
Token Validation: Verifies the reset token is valid and not expired
Token Matching: Ensures stored reset token matches provided token
Security Features
Token Expiration
- Access Token: Configurable expiration (default: multiple days)
- Refresh Token: Longer expiration for seamless re-authentication
- Reset Token: Short-lived (1 hour) for security
Password Security
- Hashing: Uses bcrypt for secure password hashing
- Validation: Implements password strength requirements
- Reset Protection: Tokens are single-use and time-limited
OAuth Security
- State Validation: Prevents CSRF attacks
- Secure Redirects: Validates redirect URLs
- Token Handling: Secure OAuth token exchange
Error Handling
Common HTTP status codes returned by authentication endpoints:
Status Code | Description |
---|---|
200 | Success |
201 | User created successfully |
400 | Bad request (validation error) |
401 | Unauthorized (invalid credentials) |
404 | Resource not found |
503 | Service unavailable (OAuth provider issue) |
Configuration
Authentication behavior is controlled by these environment variables:
ACCESS_TOKEN_EXPIRATION_DAYS=7
REFRESH_TOKEN_EXPIRATION_DAYS=30
FRONTEND_URL=http://localhost:3000
JWT_SECRET=your-secret-key
Ensure JWT_SECRET
is a strong, randomly generated key in production.
Integration Examples
Frontend Login Flow
// Login user
const response = await fetch('/auth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
username: 'user@example.com',
password: 'password123'
})
});
const data = await response.json();
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
import requests
# Login user
response = requests.post('/auth/token', data={
'username': 'user@example.com',
'password': 'password123'
})
tokens = response.json()
access_token = tokens['access_token']
refresh_token = tokens['refresh_token']
curl -X POST "/auth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=user@example.com&password=password123"
OAuth Integration
// Redirect to OAuth provider
window.location.href = '/auth/oauth/google';
// Handle callback (in your frontend route)
const urlParams = new URLSearchParams(window.location.search);
const accessToken = urlParams.get('access_token');
const refreshToken = urlParams.get('refresh_token');
if (accessToken && refreshToken) {
localStorage.setItem('access_token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
// Redirect to dashboard
}
function OAuthLogin() {
const handleGoogleLogin = () => {
window.location.href = '/auth/oauth/google';
};
return (
<button onClick={handleGoogleLogin}>
Login with Google
</button>
);
}
Best Practices
Token Management
- Store Securely: Use secure storage (httpOnly cookies preferred)
- Refresh Proactively: Refresh tokens before expiration
- Handle Expiration: Implement automatic token refresh
- Logout Cleanup: Clear tokens on logout
Security Considerations
- HTTPS Only: Always use HTTPS in production
- Token Rotation: Implement token rotation for refresh tokens
- Rate Limiting: Apply rate limiting to auth endpoints
- Audit Logging: Log authentication events
User Experience
- Email Verification: Guide users through verification process
- Password Reset: Provide clear instructions for reset flow
- Error Messages: Show user-friendly error messages
- Loading States: Handle async operations gracefully