Skip to content

Commit e566fed

Browse files
committed
refactor: remove simple-oauth2 library
An HTTP call with built-in fetch library is used to get access token, in order to reduce external dependencies. Signed-off-by: kvmw <[email protected]>
1 parent a681a2c commit e566fed

File tree

3 files changed

+30
-128
lines changed

3 files changed

+30
-128
lines changed

package-lock.json

Lines changed: 1 addition & 107 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@
2020
},
2121
"dependencies": {
2222
"dotenv": "^17.2.0",
23-
"express": "^5.1.0",
24-
"simple-oauth2": "^5.1.0"
23+
"express": "^5.1.0"
2524
},
2625
"devDependencies": {
2726
"eslint": "^9.31.0",

src/oauth2.js

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,43 @@
1-
import { ClientCredentials } from 'simple-oauth2';
21
import services from './vcap-services.js';
32

43
const credentials = services.getCredentials('p.config-server');
54

6-
const client = new ClientCredentials({
7-
client: {
8-
id: credentials.client_id,
9-
secret: credentials.client_secret,
10-
},
11-
auth: {
12-
tokenHost: credentials.access_token_uri.replace('/oauth/token', ''),
13-
tokenPath: '/oauth/token',
14-
},
15-
});
16-
175
let token = null;
186

7+
// Checks if token is expired or will be expired in given window.
8+
const expired = (token, expirationWindowSeconds = 0) => {
9+
return (
10+
!token ||
11+
token.expires_at - (Date.now() + expirationWindowSeconds * 1000) <= 0
12+
);
13+
};
14+
1915
// Requests an access token from the UAA server using client credentials.
2016
const getAccessToken = async () => {
2117
// If token is not set or expired, request a new one.
22-
if (!token || token.expired(10)) {
23-
try {
24-
token = await client.getToken();
25-
} catch (error) {
26-
console.error('Failed to get access token', error.message);
27-
throw error;
18+
if (!token || expired(token, 10)) {
19+
const response = await fetch(credentials.access_token_uri, {
20+
method: 'POST',
21+
headers: {
22+
'Content-Type': 'application/x-www-form-urlencoded',
23+
Authorization: `Basic ${Buffer.from(`${credentials.client_id}:${credentials.client_secret}`).toString('base64')}`,
24+
},
25+
body: new URLSearchParams({ grant_type: 'client_credentials' }),
26+
});
27+
28+
if (!response.ok) {
29+
throw new Error(`HTTP error! status: ${response.status}`);
2830
}
31+
32+
const data = await response.json();
33+
34+
token = {
35+
access_token: data.access_token,
36+
expires_at: Date.now() + data.expires_in * 1000,
37+
};
2938
}
3039

31-
return token.token.access_token;
40+
return token.access_token;
3241
};
3342

3443
export default {

0 commit comments

Comments
 (0)