0
# Authorization Code Grant
1
2
The Authorization Code Grant is used for web applications where the client can securely store credentials and the user authorizes the application through a browser redirect. This is the most common OAuth 2.0 flow for web applications.
3
4
## Overview
5
6
This grant type implements the OAuth 2.0 Authorization Code flow, which involves:
7
1. Redirecting users to the authorization server
8
2. Receiving an authorization code via callback
9
3. Exchanging the authorization code for an access token
10
11
## Core Import
12
13
```javascript
14
const { AuthorizationCode } = require('simple-oauth2');
15
```
16
17
## Authorization Code Class
18
19
### Constructor
20
21
```typescript { .api }
22
constructor(options: OAuth2Config): AuthorizationCode
23
```
24
25
Creates a new AuthorizationCode instance with OAuth 2.0 configuration validation.
26
27
**Parameters:**
28
- `options` - OAuth 2.0 configuration object (see main documentation)
29
30
**Example:**
31
```javascript
32
const client = new AuthorizationCode({
33
client: {
34
id: 'your-client-id',
35
secret: 'your-client-secret'
36
},
37
auth: {
38
tokenHost: 'https://oauth-provider.com',
39
authorizePath: '/oauth/authorize',
40
tokenPath: '/oauth/token'
41
}
42
});
43
```
44
45
### Generate Authorization URL
46
47
```typescript { .api }
48
authorizeURL(params: AuthorizeParams): string
49
```
50
51
Creates the authorization URL for redirecting users to the authorization server.
52
53
**Parameters:**
54
- `params.redirectURI` (string) - Registered application URI where user is redirected after authentication
55
- `params.scope` (string | string[], optional) - Application privileges requested
56
- `params.state` (string, optional) - Opaque value to maintain state between request and callback
57
- Additional parameters are automatically serialized as query parameters
58
59
**Returns:** Complete authorization URL as string
60
61
**Example:**
62
```javascript
63
const authorizationUri = client.authorizeURL({
64
redirectURI: 'http://localhost:3000/callback',
65
scope: ['read', 'write'],
66
state: 'random-state-string'
67
});
68
69
// Redirect user to authorizationUri
70
console.log('Redirect to:', authorizationUri);
71
```
72
73
### Exchange Code for Token
74
75
```typescript { .api }
76
getToken(params: TokenParams, httpOptions?: any): Promise<AccessToken>
77
```
78
79
Exchanges the authorization code for an access token.
80
81
**Parameters:**
82
- `params.code` (string) - Authorization code received from callback
83
- `params.redirectURI` (string) - Same redirect URI used in authorization request
84
- `params.scope` (string | string[], optional) - Subset of original scopes to request
85
- Additional parameters are automatically serialized for the token request
86
- `httpOptions` (object, optional) - HTTP options passed to underlying request library
87
88
**Returns:** Promise resolving to AccessToken instance
89
90
**Example:**
91
```javascript
92
// Handle callback (e.g., in Express route)
93
app.get('/callback', async (req, res) => {
94
const { code, state } = req.query;
95
96
const tokenParams = {
97
code: code,
98
redirectURI: 'http://localhost:3000/callback'
99
};
100
101
try {
102
const accessToken = await client.getToken(tokenParams);
103
console.log('Access token:', accessToken.token);
104
105
// Store token for future use
106
req.session.token = accessToken.token;
107
res.redirect('/dashboard');
108
} catch (error) {
109
console.error('Access Token Error', error.message);
110
res.status(500).json('Authentication failed');
111
}
112
});
113
```
114
115
### Create Token from Object
116
117
```typescript { .api }
118
createToken(token: any): AccessToken
119
```
120
121
Creates an AccessToken instance from a plain token object (e.g., from storage).
122
123
**Parameters:**
124
- `token` - Plain object representing an access token conforming to RFC 6750
125
126
**Returns:** AccessToken instance with full token management capabilities
127
128
**Example:**
129
```javascript
130
// Restore token from storage
131
const storedToken = JSON.parse(localStorage.getItem('oauth_token'));
132
const accessToken = client.createToken(storedToken);
133
134
// Check if token needs refresh
135
if (accessToken.expired()) {
136
const refreshedToken = await accessToken.refresh();
137
localStorage.setItem('oauth_token', JSON.stringify(refreshedToken.token));
138
}
139
```
140
141
## Type Definitions
142
143
```typescript { .api }
144
interface AuthorizeParams {
145
redirectURI: string;
146
scope?: string | string[];
147
state?: string;
148
[key: string]: any;
149
}
150
151
interface TokenParams {
152
code: string;
153
redirectURI: string;
154
scope?: string | string[];
155
[key: string]: any;
156
}
157
```
158
159
## Common Usage Pattern
160
161
```javascript
162
const { AuthorizationCode } = require('simple-oauth2');
163
164
// 1. Configure client
165
const client = new AuthorizationCode({
166
client: {
167
id: process.env.CLIENT_ID,
168
secret: process.env.CLIENT_SECRET
169
},
170
auth: {
171
tokenHost: 'https://accounts.google.com',
172
authorizePath: '/o/oauth2/auth',
173
tokenPath: '/o/oauth2/token'
174
}
175
});
176
177
// 2. Redirect to authorization URL
178
const authorizationUri = client.authorizeURL({
179
redirectURI: 'http://localhost:3000/callback',
180
scope: 'profile email',
181
state: generateRandomState()
182
});
183
184
// 3. Handle callback and exchange code
185
const tokenParams = {
186
code: req.query.code,
187
redirectURI: 'http://localhost:3000/callback'
188
};
189
190
const accessToken = await client.getToken(tokenParams);
191
192
// 4. Use token for API calls
193
const userProfile = await fetch('https://api.example.com/profile', {
194
headers: {
195
'Authorization': `Bearer ${accessToken.token.access_token}`
196
}
197
});
198
```