Overview
Daily Tracker API uses JSON Web Tokens (JWT) for authentication. The API supports two authentication methods:- Email/Password Authentication: Traditional registration and login with JWT tokens
- Google OAuth2: Social login with Google accounts
/api/* require authentication, while authentication endpoints (/auth/*) and health checks are public.
The API uses stateless JWT authentication with refresh tokens for session management. Tokens are signed using HMAC-SHA256 algorithm.
Authentication Flow
Here’s the high-level authentication flow:Register or Login
User creates an account with
/auth/register or logs in with /auth/login (or uses Google OAuth2).JWT Token Structure
Daily Tracker API uses JJWT library (version 0.12.6) to generate and validate tokens. Let’s examine the token structure:Token Configuration
Fromapplication.yaml:src/main/resources/application.yaml:52-54:
Access Token Structure
The JWT access token contains the following claims (fromJwtService.java:src/main/java/com/dailytracker/api/security/JwtService.java:30-38):
- Algorithm: HMAC-SHA256 (HS256)
- Signing Key: Derived from
JWT_SECRETenvironment variable - Expiration: 24 hours (86400000 ms) from issue time
- Claims: Contains user ID in both
subanduserIdfields
Registration
Create a new user account with email and password.Endpoint
Request Body
Validation Rules
FromRegisterRequest.java:src/main/java/com/dailytracker/api/dto/request/RegisterRequest.java:
email: Required, valid email format, max 254 characterspassword: Required, minimum 6 characterslanguage: Optional, must be one of:pt-BR,en-US,es
Password Security
Passwords are hashed using BCrypt before storage. The API uses Spring Security’sBCryptPasswordEncoder with default strength (10 rounds).
Example Request
cURL
Response
Login
Authenticate with email and password to receive JWT tokens.Endpoint
Request Body
Example Request
cURL
Response
FromAuthResponse.java:src/main/java/com/dailytracker/api/dto/response/AuthResponse.java:
token: JWT access token (valid for 24 hours)refreshToken: UUID-based refresh token (valid for 30 days)type: Always “Bearer” for use in Authorization headers
Making Authenticated Requests
Once you have an access token, include it in theAuthorization header with the Bearer scheme:
cURL
Authorization Header Format
How It Works
FromJwtAuthenticationFilter.java:src/main/java/com/dailytracker/api/security/JwtAuthenticationFilter.java:
Extract Token
The JWT filter extracts the token from the
Authorization header, removing the “Bearer ” prefix.Token Validation
FromJwtService.java:src/main/java/com/dailytracker/api/security/JwtService.java:54-61:
- Valid signature (signed with correct secret)
- Not expired
- Valid JSON structure
- Contains required claims
Token Refresh
When your access token expires (after 24 hours), use the refresh token to obtain a new access token without requiring the user to log in again.Endpoint
Request Body
Example Request
cURL
Response
- A new access token with a fresh 24-hour expiration
- A new refresh token with a fresh 30-day expiration
Refresh tokens are stored in the database and are single-use. When you use a refresh token, it’s invalidated and a new one is issued.
Refresh Token Lifecycle
- Creation: Generated as a UUID when user logs in
- Storage: Stored in the database with user association and expiration
- Validation: Checked for existence, ownership, and expiration
- Rotation: Invalidated and replaced when used
- Expiration: Automatically expires after 30 days
Google OAuth2 Login
Daily Tracker supports social login with Google accounts using OAuth2.Configuration
Fromapplication.yaml:src/main/resources/application.yaml:30-43:
OAuth2 Flow
User Creation/Linking
From
OAuth2SuccessHandler.java:src/main/java/com/dailytracker/api/security/OAuth2SuccessHandler.java:41-55:- If user exists with Google ID → use existing account
- If user exists with same email → link Google ID to account
- If new user → create new account with Google ID
Initiating Google Login
Frontend Implementation:OAuth2 Token Delivery
FromOAuth2SuccessHandler.java:src/main/java/com/dailytracker/api/security/OAuth2SuccessHandler.java:63-71:
The OAuth2 success handler returns an HTML page that:
- Popup Flow: Uses
window.opener.postMessage()to send tokens to the parent window - Fallback: Redirects to frontend with tokens in URL query parameters
Google Account Linking
If a user previously registered with email/password and then logs in with Google using the same email:- The Google ID is automatically linked to the existing account
- User maintains access to all their existing data
- User can subsequently login with either method
Security Configuration
FromSecurityConfig.java:src/main/java/com/dailytracker/api/config/SecurityConfig.java:33-44:
Public Endpoints (No Authentication Required)
Protected Endpoints (Authentication Required)
/api/ require a valid JWT token in the Authorization header.
Session Management
FromSecurityConfig.java:src/main/java/com/dailytracker/api/config/SecurityConfig.java:30-32:
- JWT authentication is stateless (no server-side sessions)
- Sessions are only created for OAuth2 flows (IF_REQUIRED)
- CSRF protection is disabled (stateless API)
Best Practices
Token Storage
Browser Applications
Store tokens in
localStorage or sessionStorage. Use httpOnly cookies for enhanced security if possible.Mobile Applications
Use secure storage mechanisms like iOS Keychain or Android Keystore.
Server-to-Server
Store refresh tokens in secure, encrypted storage. Keep access tokens in memory only.
Single Page Apps
Implement token refresh logic before expiration to maintain seamless UX.
Token Refresh Strategy
Implement proactive token refresh:Error Handling
Handle authentication errors gracefully:| Status Code | Error | Action |
|---|---|---|
401 | Invalid or expired token | Refresh token or redirect to login |
403 | Valid token but insufficient permissions | Show error message |
404 | User not found | Token valid but user deleted - logout |
Security Recommendations
Example: Complete Authentication Flow
Here’s a complete example implementing the full authentication lifecycle:Example Client Implementation
Next Steps
Now that you understand authentication, explore the API:User API
Manage user profiles and preferences
Tasks API
Create and manage tasks with full CRUD operations
Projects API
Organize tasks into projects
AI Assistant
Integrate AI-powered task assistance