66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
import axios from 'axios';
|
|
|
|
interface TokenResponse {
|
|
access_token: string;
|
|
expires_in: number;
|
|
token_type: string;
|
|
}
|
|
|
|
export default class CognitoClient {
|
|
tokenEndpont: string;
|
|
clientId: string;
|
|
clientSecret: string;
|
|
scope: string;
|
|
expiresAt: number;
|
|
accessToken: string;
|
|
|
|
constructor(
|
|
tokenEndpoint: string,
|
|
clientId: string,
|
|
clientSecret: string,
|
|
scope: string,
|
|
) {
|
|
this.tokenEndpont = `${tokenEndpoint}/oauth2/token`;
|
|
this.clientId = clientId;
|
|
this.clientSecret = clientSecret;
|
|
this.scope = scope;
|
|
this.accessToken = '';
|
|
this.expiresAt = 0;
|
|
}
|
|
|
|
private getPostData(): URLSearchParams {
|
|
const params = new URLSearchParams();
|
|
params.append('grant_type', 'client_credentials');
|
|
params.append('client_id', this.clientId);
|
|
params.append('scope', this.scope);
|
|
return params;
|
|
}
|
|
|
|
public async getToken(): Promise<string> {
|
|
const now = Date.now();
|
|
if (this.expiresAt < now) {
|
|
await this.getNewToken();
|
|
}
|
|
console.log('Getting cached token');
|
|
return this.accessToken;
|
|
}
|
|
|
|
private async getNewToken(): Promise<void> {
|
|
console.log('Getting new token');
|
|
const authString =
|
|
'Basic ' +
|
|
Buffer.from(this.clientId + ':' + this.clientSecret).toString('base64');
|
|
const res: TokenResponse = await axios
|
|
.post(this.tokenEndpont, this.getPostData(), {
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
Authorization: authString,
|
|
},
|
|
})
|
|
.then((r) => r.data);
|
|
|
|
this.accessToken = res.access_token;
|
|
this.expiresAt = Date.now() + res.expires_in * 1e3;
|
|
}
|
|
}
|