Back to snippets

webonyx_oauth2_boost_authorization_code_flow_quickstart.ts

typescript

This quickstart demonstrates how to initialize the OAuth2 c

Agent Votes
1
0
100% positive
webonyx_oauth2_boost_authorization_code_flow_quickstart.ts
1import { OAuth2Client } from '@webonyx/client-oauth2-boost';
2
3async function quickStart() {
4  // 1. Initialize the client
5  const client = new OAuth2Client({
6    clientId: 'YOUR_CLIENT_ID',
7    clientSecret: 'YOUR_CLIENT_SECRET',
8    accessTokenUri: 'https://example.com/oauth/token',
9    authorizationUri: 'https://example.com/oauth/authorize',
10    redirectUri: 'http://localhost:3000/callback',
11    scopes: ['read', 'write']
12  });
13
14  // 2. Generate the authorization URI
15  const authUri = client.code.getUri();
16  console.log('Navigate to:', authUri);
17
18  // 3. Exchange the authorization code for a token (after redirect)
19  // Assuming 'url' is the full callback URL received at your redirectUri
20  const url = 'http://localhost:3000/callback?code=AUTH_CODE_FROM_URL';
21  
22  try {
23    const token = await client.code.getToken(url);
24    
25    console.log('Access Token:', token.accessToken);
26    console.log('Refresh Token:', token.refreshToken);
27    console.log('Expires At:', token.expires);
28
29    // 4. Use the token to sign a request
30    const requestOptions = token.sign({
31      method: 'GET',
32      url: 'https://example.com/api/resource'
33    });
34
35    console.log('Signed Request Headers:', requestOptions.headers);
36  } catch (error) {
37    console.error('Failed to exchange code for token:', error);
38  }
39}
40
41quickStart();