Created
August 22, 2023 07:57
-
-
Save ANovokmet/79c2ac9e958cb5ea09098c12d5567310 to your computer and use it in GitHub Desktop.
Fetch IdentityServer OAuth token using NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require('https'); | |
const querystring = require('querystring'); | |
const fs = require('fs'); | |
const username = 'user'; | |
const password = 'user123'; | |
const baseAddress = `https://my-auth-server.com`; | |
const config = { | |
'client_id': 'myapi', | |
'client_secret': 'secret', | |
'grant_type': 'password', | |
'scope': 'openid myapiscope', | |
'username': username, | |
'password': password | |
} | |
const data = querystring.stringify(config); | |
const options = { | |
hostname: `my-auth-server.com`, | |
port: 443, | |
path: '/connect/token', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': data.length | |
} | |
} | |
function requestToken() { | |
const req = https.request(options, res => { | |
res.on('data', d => { | |
console.log(res.statusCode) | |
if(res.statusCode == 200) { | |
const response = JSON.parse(d); | |
console.log('Fetched token successfully'); | |
console.log(JSON.stringify(response, null, 4)); | |
save(response.access_token); | |
} | |
}); | |
}); | |
req.on('error', error => { | |
console.error(error); | |
}); | |
req.write(data); | |
req.end(); | |
} | |
function save(token) { | |
fs.writeFile("./token.txt", token, function (err) { | |
if (err) { | |
return console.log(err); | |
} | |
console.log("The file was saved!"); | |
}); | |
} | |
requestToken(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const authorization = require('./token'); | |
// ... | |
const headers = { | |
'Authorization': authorization, | |
'Content-Type': 'application/json' | |
} | |
// ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const contents = fs.readFileSync('./token.txt', 'utf8'); | |
module.exports = `Bearer ${contents}`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment