62 lines
1.6 KiB
JavaScript
62 lines
1.6 KiB
JavaScript
const axios = require('axios');
|
|
const qs = require('qs');
|
|
|
|
|
|
class OAuth2Client {
|
|
constructor(config) {
|
|
this.tokenUrl = config.token_url;
|
|
this.introspectionUrl = config.introspection_url;
|
|
this.clientId = config.client_id;
|
|
this.clientSecret = config.client_secret;
|
|
|
|
const authUrl = config.authorization_url;
|
|
const authArgs = new URLSearchParams({
|
|
response_type: 'code',
|
|
client_id: this.clientId
|
|
}).toString();
|
|
this.authUrl = `${authUrl}?${authArgs}`;
|
|
|
|
this.session = axios.create({
|
|
auth: {
|
|
username: this.clientId,
|
|
password: this.clientSecret
|
|
},
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
}
|
|
});
|
|
}
|
|
|
|
async exchangeCodeForToken(code) {
|
|
const data = qs.stringify({
|
|
grant_type: 'authorization_code',
|
|
code,
|
|
client_id: this.clientId,
|
|
client_secret: this.clientSecret
|
|
});
|
|
|
|
const response = await axios.post(this.tokenUrl, data, {
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
|
|
});
|
|
|
|
return response.data;
|
|
}
|
|
|
|
async introspectToken(token) {
|
|
const data = qs.stringify({
|
|
token,
|
|
client_id: this.clientId,
|
|
client_secret: this.clientSecret
|
|
});
|
|
|
|
const response = await axios.post(this.introspectionUrl, data, {
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
|
|
});
|
|
|
|
return response.data;
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = OAuth2Client
|