In this lab, you will build a mock implementation of the OAuth 2.0 Authorization Code flow. You will simulate the Client, the Authorization Server, and the Resource Server to see exactly how tokens move through the system.
The client must initiate the flow by redirecting the user to the server. You will craft this URL using the required parameters: `client_id`, `response_type`, `scope`, and `state`.
๐ก Notice the `state` parameter. In your implementation, you must verify that the state returned by the server matches the state you sent.
Once the client receives the `code` via the redirect, it must exchange it for an access token using a secure back-channel POST request.
async function exchangeCodeForToken(code) {
const response = await fetch('https://mock-auth.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
client_id: 'app_123',
client_secret: 'SUPER_SECRET_KEY'
})
});
return response.json();
}The `client_secret` is the key here. Only a confidential client (one with a backend) can perform this exchange securely.
| Component | Input | Output | Security Criticality |
|---|---|---|---|
| Auth Request | client_id + state | Auth Code | High (Redirect URI) |
| Token Request | code + secret | Access Token | Critical (Secret Leak) |
| Resource Request | Access Token | User Data | Medium (Token Expiry) |
Now, try to break your implementation. Attempt to use a code that has already been used, or change the `state` parameter in the callback.
In a real-world app, never store the `client_secret` in frontend code. Use a backend service to handle the token exchange.
Verify exercises to earn โ 220 XP and unlock next lab level.