Skip to content

Commit 9e29034

Browse files
Update API usage example
1 parent 293c15c commit 9e29034

File tree

1 file changed

+72
-112
lines changed

1 file changed

+72
-112
lines changed

README.md

Lines changed: 72 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ npm install --save simple-oauth2
5454
With a minimal configuration, create a client instance of any supported [grant type](#supported-grant-types).
5555

5656
```javascript
57+
import { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } from 'simple-oauth2';
58+
5759
const config = {
5860
client: {
5961
id: '<client-id>',
@@ -63,8 +65,6 @@ const config = {
6365
tokenHost: 'https://api.oauth.com'
6466
}
6567
};
66-
67-
const { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } = require('simple-oauth2');
6868
```
6969

7070
For a complete reference of configuration options, see the [API Options](./API.md#options)
@@ -78,32 +78,28 @@ Depending on your use-case, any of the following supported grant types may be us
7878
The [Authorization Code](https://oauth.net/2/grant-types/authorization-code/) grant type is used by confidential and public clients to exchange an authorization code for an access token. After the user returns to the client via the redirect URL, the application will get the authorization code from the URL and use it to request an access token.
7979

8080
```javascript
81-
async function run() {
82-
const client = new AuthorizationCode(config);
81+
const client = new AuthorizationCode(config);
8382

84-
const authorizationUri = client.authorizeURL({
85-
redirect_uri: 'http://localhost:3000/callback',
86-
scope: '<scope>',
87-
state: '<state>'
88-
});
83+
const authorizationUri = client.authorizeURL({
84+
redirect_uri: 'http://localhost:3000/callback',
85+
scope: '<scope>',
86+
state: '<state>'
87+
});
8988

90-
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
91-
res.redirect(authorizationUri);
89+
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
90+
res.redirect(authorizationUri);
9291

93-
const tokenParams = {
94-
code: '<code>',
95-
redirect_uri: 'http://localhost:3000/callback',
96-
scope: '<scope>',
97-
};
92+
const tokenParams = {
93+
code: '<code>',
94+
redirect_uri: 'http://localhost:3000/callback',
95+
scope: '<scope>',
96+
};
9897

99-
try {
100-
const accessToken = await client.getToken(tokenParams);
101-
} catch (error) {
102-
console.log('Access Token Error', error.message);
103-
}
98+
try {
99+
const accessToken = await client.getToken(tokenParams);
100+
} catch (error) {
101+
console.log('Access Token Error', error.message);
104102
}
105-
106-
run();
107103
```
108104

109105
See the [API reference](./API.md#new-authorizationcodeoptions) for a complete reference of available options or any of our available examples at the [example folder](./example).
@@ -113,23 +109,19 @@ See the [API reference](./API.md#new-authorizationcodeoptions) for a complete re
113109
The [Resource Owner Password Credentials](https://oauth.net/2/grant-types/password/) grant type is a way to exchange a user's credentials for an access token. Because the client application has to collect the user's password and send it to the authorization server, it is not recommended that this grant be used at all anymore.
114110

115111
```javascript
116-
async function run() {
117-
const client = new ResourceOwnerPassword(config);
112+
const client = new ResourceOwnerPassword(config);
118113

119-
const tokenParams = {
120-
username: 'username',
121-
password: 'password',
122-
scope: '<scope>',
123-
};
114+
const tokenParams = {
115+
username: 'username',
116+
password: 'password',
117+
scope: '<scope>',
118+
};
124119

125-
try {
126-
const accessToken = await client.getToken(tokenParams);
127-
} catch (error) {
128-
console.log('Access Token Error', error.message);
129-
}
120+
try {
121+
const accessToken = await client.getToken(tokenParams);
122+
} catch (error) {
123+
console.log('Access Token Error', error.message);
130124
}
131-
132-
run();
133125
```
134126

135127
See the [API reference](./API.md#new-resourceownerpasswordoptions) for a complete reference of available options.
@@ -139,21 +131,17 @@ See the [API reference](./API.md#new-resourceownerpasswordoptions) for a complet
139131
The [Client Credentials](https://oauth.net/2/grant-types/client-credentials/) grant type is used by clients to obtain an access token outside of the context of a user. This is typically used by clients to access resources about themselves rather than to access a user's resources.
140132

141133
```javascript
142-
async function run() {
143-
const client = new ClientCredentials(config);
134+
const client = new ClientCredentials(config);
144135

145-
const tokenParams = {
146-
scope: '<scope>',
147-
};
136+
const tokenParams = {
137+
scope: '<scope>',
138+
};
148139

149-
try {
150-
const accessToken = await client.getToken(tokenParams);
151-
} catch (error) {
152-
console.log('Access Token error', error.message);
153-
}
140+
try {
141+
const accessToken = await client.getToken(tokenParams);
142+
} catch (error) {
143+
console.log('Access Token error', error.message);
154144
}
155-
156-
run();
157145
```
158146

159147
See the [API reference](./API.md#new-clientcredentialsoptions) for a complete reference of available options.
@@ -168,65 +156,49 @@ On long lived applications, it is often necessary to refresh access tokens. In s
168156

169157

170158
```javascript
171-
async function run() {
172-
const accessTokenJSONString = JSON.stringify(accessToken);
159+
const accessTokenJSONString = JSON.stringify(accessToken);
173160

174-
await persistAccessTokenJSON(accessTokenJSONString);
175-
}
176-
177-
run();
161+
await persistAccessTokenJSON(accessTokenJSONString);
178162
```
179163

180164
By the time we need to refresh the persistent access token, we can get back an [AccessToken](./API.md#accesstoken) instance by using the client's [.createToken](./API.md#createtokentoken--accesstoken) method.
181165

182166
```javascript
183-
async function run() {
184-
const accessTokenJSONString = await getPersistedAccessTokenJSON();
185-
186-
let accessToken = client.createToken(JSON.parse(accessTokenJSONString));
187-
}
167+
const accessTokenJSONString = await getPersistedAccessTokenJSON();
188168

189-
run();
169+
let accessToken = client.createToken(JSON.parse(accessTokenJSONString));
190170
```
191171

192172
Once we have determined the access token needs refreshing with the [.expired()](./API.md#expiredexpirationwindowseconds--boolean) method, we can finally refresh it with a [.refresh()](./API.md#await-refreshparams--accesstoken) method call.
193173

194174
```javascript
195-
async function run() {
196-
if (accessToken.expired()) {
197-
try {
198-
const refreshParams = {
199-
scope: '<scope>',
200-
};
201-
202-
accessToken = await accessToken.refresh(refreshParams);
203-
} catch (error) {
204-
console.log('Error refreshing access token: ', error.message);
205-
}
175+
if (accessToken.expired()) {
176+
try {
177+
const refreshParams = {
178+
scope: '<scope>',
179+
};
180+
181+
accessToken = await accessToken.refresh(refreshParams);
182+
} catch (error) {
183+
console.log('Error refreshing access token: ', error.message);
206184
}
207185
}
208-
209-
run();
210186
```
211187

212188
The [.expired()](./API.md##expiredexpirationwindowseconds--boolean) helper is useful for knowing when a token has definitively expired. However, there is a common race condition when tokens are near expiring. If an OAuth 2.0 token is issued with a `expires_in` property (as opposed to an `expires_at` property), there can be discrepancies between the time the OAuth 2.0 server issues the access token and when it is received.
213189

214190
These come down to factors such as network and processing latency and can be worked around by preemptively refreshing the access token:
215191

216192
```javascript
217-
async function run() {
218-
const EXPIRATION_WINDOW_IN_SECONDS = 300; // Window of time before the actual expiration to refresh the token
219-
220-
if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)) {
221-
try {
222-
accessToken = await accessToken.refresh();
223-
} catch (error) {
224-
console.log('Error refreshing access token: ', error.message);
225-
}
193+
const EXPIRATION_WINDOW_IN_SECONDS = 300; // Window of time before the actual expiration to refresh the token
194+
195+
if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)) {
196+
try {
197+
accessToken = await accessToken.refresh();
198+
} catch (error) {
199+
console.log('Error refreshing access token: ', error.message);
226200
}
227201
}
228-
229-
run();
230202
```
231203

232204
**Warning:** Tokens obtained with the Client Credentials grant may not be refreshed. Fetch a new token when it's expired.
@@ -238,31 +210,23 @@ See the [API reference](./API.md#accesstoken) for a complete reference of availa
238210
When you've done with the token or you want to log out, you can revoke both access and refresh tokens.
239211

240212
```javascript
241-
async function run() {
242-
try {
243-
await accessToken.revoke('access_token');
244-
await accessToken.revoke('refresh_token');
245-
} catch (error) {
246-
console.log('Error revoking token: ', error.message);
247-
}
213+
try {
214+
await accessToken.revoke('access_token');
215+
await accessToken.revoke('refresh_token');
216+
} catch (error) {
217+
console.log('Error revoking token: ', error.message);
248218
}
249-
250-
run();
251219
```
252220

253221
As a convenience method, you can also revoke both tokens in a single call:
254222

255223
```javascript
256-
async function run() {
257-
try {
258-
// Revokes both tokens, refresh token is only revoked if the access_token is properly revoked
259-
await accessToken.revokeAll();
260-
} catch (error) {
261-
console.log('Error revoking token: ', error.message);
262-
}
224+
try {
225+
// Revokes both tokens, refresh token is only revoked if the access_token is properly revoked
226+
await accessToken.revokeAll();
227+
} catch (error) {
228+
console.log('Error revoking token: ', error.message);
263229
}
264-
265-
run();
266230
```
267231

268232
See the [API reference](./API.md#accesstoken) for a complete reference of available options.
@@ -272,18 +236,14 @@ See the [API reference](./API.md#accesstoken) for a complete reference of availa
272236
Whenever a client or server error is produced, a [boom](https://github.com/hapijs/boom) error is thrown by the library. As such any [boom error property](https://hapi.dev/module/boom/api) is available, but the exact information may vary according to the type of error.
273237

274238
```javascript
275-
async function run() {
276-
const client = new ClientCredentials(config);
239+
const client = new ClientCredentials(config);
277240

278-
try {
279-
await client.getToken();
280-
} catch(error) {
281-
console.log(error.output);
282-
}
241+
try {
242+
await client.getToken();
243+
} catch(error) {
244+
console.log(error.output);
283245
}
284246

285-
run();
286-
287247
// { statusCode: 401,
288248
// payload:
289249
// { statusCode: 401,

0 commit comments

Comments
 (0)