|
1 | | -import { ClientCredentials } from 'simple-oauth2'; |
2 | 1 | import services from './vcap-services.js'; |
3 | 2 |
|
4 | 3 | const credentials = services.getCredentials('p.config-server'); |
5 | 4 |
|
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 | | - |
17 | 5 | let token = null; |
18 | 6 |
|
| 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 | + |
19 | 15 | // Requests an access token from the UAA server using client credentials. |
20 | 16 | const getAccessToken = async () => { |
21 | 17 | // 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}`); |
28 | 30 | } |
| 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 | + }; |
29 | 38 | } |
30 | 39 |
|
31 | | - return token.token.access_token; |
| 40 | + return token.access_token; |
32 | 41 | }; |
33 | 42 |
|
34 | 43 | export default { |
|
0 commit comments