API tokens are often treated as minor implementation details, but they pose significant security risks. Even correctly signed tokens can be stolen, and their long-term validity allows attackers to impersonate legitimate users.
For public clients like single-page applications, the Authorization Code Flow with PKCE is the standard. It binds authorization requests to a temporary verification secret, preventing attackers from completing the exchange if they intercept the code.
Token lifetime requires balancing user experience with security. Access tokens for browser applications should typically last 5 to 15 minutes. Refresh tokens can last up to 7 days, with an absolute session limit of 30 days to prevent indefinite access.
Storing tokens in localStorage or sessionStorage is insecure, as any injected script can read them. Using HttpOnly cookies with Secure, SameSite, and __Host attributes significantly reduces the risk of token theft via XSS attacks.
The most secure architecture for browser applications is the Backend for Frontend (BFF) pattern. In this model, tokens never reach the browser; instead, the BFF manages sessions server-side, keeping sensitive credentials isolated from client-side vulnerabilities.






