Overview
TecMeli implements OAuth 2.0 authentication for the Mercado Libre API using a robust token management system. The architecture ensures that every API request is automatically authenticated and tokens are seamlessly refreshed when they expire.Architecture Components
The authentication system consists of three main components:AuthInterceptor
Injects access tokens into outgoing requests
TokenAuthenticator
Handles automatic token refresh on 401 responses
TokenRepository
Manages token storage and refresh logic
How It Works
1. AuthInterceptor
TheAuthInterceptor automatically adds the Authorization header to all API requests:
The interceptor smartly skips adding tokens to the
/oauth/token endpoint to avoid circular dependencies during token refresh.2. TokenAuthenticator
When the API returns a 401 (Unauthorized) response, theTokenAuthenticator automatically refreshes the token:
3. TokenRepository
TheTokenRepository manages token storage and communicates with the Auth API:
core/network/TokenAuthenticator.kt:18core/network/AuthInterceptor.kt:15data/repository/TokenRepositoryImpl.kt:22
OAuth 2.0 Flow
Initial Configuration
The app is configured with
clientId, clientSecret, and an initial refreshToken obtained during user login.First API Request
When making the first API call,
TokenRepository.getAccessToken() is called. Since no token exists, it automatically triggers a token refresh.Automatic Refresh
TokenAuthenticator intercepts the 401 response and calls refreshToken() to obtain a new access token.API Configuration
TheApiConfig class centralizes all OAuth credentials:
- Stored securely (e.g., in encrypted SharedPreferences)
- Injected via Hilt/Dagger dependency injection
- Obtained from the Mercado Libre Developer Portal
Auth API Endpoint
TheAuthApi interface defines the token refresh endpoint:
data/remote/api/AuthApi.kt:14
Best Practices
Thread Safety
Thread Safety
The
TokenRepositoryImpl is marked as @Singleton to ensure a single source of truth for the access token across the entire application. This prevents race conditions during concurrent requests.Error Handling
Error Handling
Token refresh failures are handled gracefully by returning
null from the authenticator, which signals OkHttp to fail the request and propagate the error to the caller.Security
Security
Never log or expose tokens in production builds. Use ProGuard/R8 to obfuscate token-related code and store credentials in secure storage.
Next Steps
Network Layer
Learn about safe API calls and error handling
Error Handling
Understand how errors are mapped and handled