Skip to content

Commit c31d90d

Browse files
committed
chore: update the code
1 parent 22eefbf commit c31d90d

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

docs/use-cases/ai/connect-your-agent-to-third-party-apis.mdx

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -117,24 +117,20 @@ async function getGoogleAccessToken(userAccessToken: string) {
117117
}
118118
);
119119

120-
if (response.ok) {
121-
return response.json(); // { accessToken: "...", expiresAt: 1700000000 }
122-
}
123-
124-
if (response.status === 404) {
125-
return null; // User hasn't authorized Google yet
126-
}
127-
128-
throw new Error('Failed to retrieve access token');
120+
return response.json();
129121
}
130122
```
131123

132124
### Step 2: Request authorization if needed \{#step-2-request-authorization-if-needed}
133125

134-
If no token exists, use Logto's [Social Verification API](/secret-vault/federated-token-set#reauthentication-and-token-renewal) to initiate the authorization flow:
126+
If no token exists, the token has expired, or you need to extend the access token's scope, use Logto's [Social Verification API](/secret-vault/federated-token-set#reauthentication-and-token-renewal) to initiate the authorization flow:
135127

136128
```tsx
137129
async function requestGoogleAuthorization(userAccessToken: string, scopes: string) {
130+
// Generate a random state for CSRF protection
131+
const state = crypto.randomUUID();
132+
sessionStorage.setItem('oauth_state', state);
133+
138134
// Initiate social verification
139135
const response = await fetch('https://[tenant-id].logto.app/api/verification/social', {
140136
method: 'POST',
@@ -144,6 +140,7 @@ async function requestGoogleAuthorization(userAccessToken: string, scopes: strin
144140
},
145141
body: JSON.stringify({
146142
connectorId: '<google_connector_id>',
143+
state,
147144
redirectUri: 'https://your-ai-agent.com/callback',
148145
scope: scopes,
149146
}),
@@ -169,9 +166,15 @@ async function handleAuthorizationCallback(
169166
callbackParams: URLSearchParams
170167
) {
171168
const verificationRecordId = sessionStorage.getItem('verificationRecordId');
169+
const storedState = sessionStorage.getItem('oauth_state');
172170
const code = callbackParams.get('code');
173171
const state = callbackParams.get('state');
174172

173+
// Validate state to prevent CSRF attacks
174+
if (state !== storedState) {
175+
throw new Error('Invalid state parameter');
176+
}
177+
175178
// Verify the authorization
176179
await fetch('https://[tenant-id].logto.app/api/verification/social/verify', {
177180
method: 'POST',
@@ -200,6 +203,10 @@ async function handleAuthorizationCallback(
200203
verificationRecordId,
201204
}),
202205
});
206+
207+
// Clean up
208+
sessionStorage.removeItem('verificationRecordId');
209+
sessionStorage.removeItem('oauth_state');
203210
}
204211
```
205212

0 commit comments

Comments
 (0)