Authorization and Authentication to REST API from JavaScript Client
Building a PHP REST API for external JavaScript clients introduces specific architectural challenges, particularly regarding how users authenticate and how you manage session state across different domains. You correctly identified that storing user credentials on the client side is a security anti-pattern. The solution involves issuing an opaque token upon successful authentication, but the mechanism for storing and managing that token requires careful consideration of browser behavior.
Handling Cross-Origin Session State
Your primary concern stems from the shared cookie context within a single browser. When User A logs out of an external application, they are clearing the state specific to that domain. However, your API's session token stored in document.cookie persists because it belongs to your service's domain. The browser has no inherent knowledge of when the user leaves the external application versus staying on their own pages; it only tracks HTTP requests and cookies associated with the current request headers.
To resolve this without relying on complex custom logic to detect "logout" events, you must decouple the storage mechanism or change the authentication flow. Storing the token in a standard document.cookie is risky for cross-origin Single Page Applications (SPAs) due to Same-Origin Policy restrictions. If your API and the external site are on different domains, JavaScript cannot read the cookie at all unless you configure the cookie as SameSite=None; Secure. Even then, relying on cookies for opaque tokens in a REST architecture often complicates state management.
A more robust pattern for this scenario is to store the token in memory (JavaScript variables) rather than on disk or in the browser's persistent storage. This ensures that when the page reloads or the user navigates away, the session effectively resets unless explicitly re-authenticated. If persistence is required across page loads within the same external domain, consider using localStorage or sessionStorage, but be aware of XSS risks. Never store sensitive tokens in document.cookie without strict security flags.
Implementing API Key and Token Rotation
Your proposed flow combines an API key with user credentials to fetch a token. This is a valid pattern for distinguishing between system-level access (the library) and user-level data. However, the logic for retrieving the initial token needs refinement regarding where it lives.
Instead of blindly reading a cookie on every request, implement a check that prioritizes in-memory storage first. Only fall back to persistent storage if the application explicitly requires it and security measures are in place. Furthermore, ensure your PHP backend validates the API key alongside the user credentials before issuing the token. This prevents unauthorized access even if the client-side library is compromised.
When handling the logout scenario, you do not need to "clear" a cookie on an external domain from your server side. You simply stop sending the authentication header in subsequent requests once the external application signals session termination. If the external site uses a local logout button that clears its own cookies, any token stored in localStorage or memory will persist until the page is refreshed or explicitly cleared by your JavaScript logic.
For high-security requirements, consider implementing token rotation where the backend issues a new short-lived token and invalidates the old one upon login. This mitigates the risk of session hijacking, though it requires the client to handle refresh tokens carefully.
Conclusion
The key takeaway is that relying on document.cookie for cross-origin authentication state is fragile. By storing the authorization token in memory or using isolated storage mechanisms like localStorage with appropriate security configurations, you ensure that a user's logout on the external application does not inadvertently maintain an active session to your API. This approach respects the boundaries of the client and maintains a clean separation between the external app's lifecycle and your service's state.