I have formatted an axios post request as follows:
var config = {
method: 'post',
url: 'https://us.battle.net/oauth/token',
headers: {
'Authorization': 'Basic ' process.env.BATTLENET_CLIENT ':' process.env.BATTLENET_SECRET,
...data.getHeaders()
},
data : data
};
This is getting rejected with a 401. However, when I generate the code snippet for this out of Postman, which functions, it is the same, except the Authorization is a seemingly random string that was generated:
var config = {
method: 'post',
url: 'https://us.battle.net/oauth/token',
headers: {
'Authorization': 'Basic reallyRandomLongStringIsNotClientIDAndSecretKey=',
...data.getHeaders()
},
data : data
};
Plugging this into my code made it work. I'm curious if there is something I'm missing when coding Basic Auth credentials, as it seems Postman has converted/encrypted it into something I can not figure out?
CodePudding user response:
You just need to encode the string with username and password/secret to Base64 like this:
const encodedAuthorization = Buffer.from(`${process.env.BATTLENET_CLIENT}:${process.env.BATTLENET_SECRET}`).toString('base64')
var config = {
method: 'post',
url: 'https://us.battle.net/oauth/token',
headers: {
'Authorization': `Basic ${encodedAuthorization}`,
...data.getHeaders()
},
data : data
};
CodePudding user response:
The Basic-Auth-Authentication-Scheme functions as follows:
- The client provides credentials in the form of a "username" and a "password".
- Username and password are concatenated with a colon: "username:password"
- The concatenated string is encoded in base64
- The header value is then the base64-encoded string prefixed with "Basic "
Below you can see a javascript implementation:
const userName = "username"
const password = "password"
const authenticationHeader = "Basic " btoa(`${userName}:${password}`)