I'm trying to sync my auth0 userinfo with my local database:
userRouter.get("/sync", validateAccessToken, (req, res) => {
var request = require("request");
var usertoken;
var options = { method: 'POST',
url: 'https://MYDOMAN.eu.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myclienttoken","client_secret":"myclientsecret","audience":"https://MYDOMAIN.eu.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
usertoken = body;
console.log(body);
});
var auth0options = {
method: "GET",
url: "https://MYDOMAIN.eu.auth0.com/api/v2/users",
params: {id: 'email:"testuser"', search_engine: 'v3'},
headers: {
"content-type": "application/json",
authorization: `Bearer` + usertoken.access_token,
},
};
axios.request(auth0options).then(function (response) {
console.log("RES DATA: ", response.data);
})
.catch(function (error) {
console.error(error);
});
console.log("called");
res.status(200).json("message");
});
The following line, results in a error:
authorization: Bearer + usertoken.access_token,
"Cannot read properties of Undefined (reading 'access_token)"
But I don't get the userinfo when calling the auth0 api with that token.
I'm using the audience from the Auth0 Management API ex:
https://MYDOMAIN.eu.auth0.com/api/v2/
And not the audience from my own API, as I have read that's the correct way:
https://mydomain
Any ideas on what I'm doing wrong?
Related
I am trying to import data into elastic search using axios and nodejs but I am getting 400 bad request error, I have created index in elastic which is sales-enable-data index I am trying to add data using that index but I am getting bad request error
Code
app.get("/import/data", async (req, res) => {
const current = {
project_name: "java",
delivery_manager: "Yawhe",
project_manager: "Ruth",
};
const data = JSON.stringify(current);
await axios({
url: "http://localhost:9200/sales-enable-data-index/_doc",
method: "POST",
headers: {
"Content-Type": "application/json",
},
auth: {
username: "username",
password: "password",
},
body: data,
})
.then((response) => {
return res.status(200).send(response);
})
.catch((err) => {
return res.status(500).send(err);
});
});
Error
"code": "ERR_BAD_REQUEST",
"status": 400
Check the Axios request. Request unable to find the endpoint
You're sending String instead of JSON, this is why ElasticSearch says it does not like the data it's receiving.
Try doing the request without the JSON.stringify like this:
app.get("/import/data", async (req, res) => {
const current = {
project_name: "java",
delivery_manager: "Yawhe",
project_manager: "Ruth",
};
await axios({
url: "http://localhost:9200/sales-enable-data-index/_doc",
method: "POST",
headers: {
"Content-Type": "application/json",
},
auth: {
username: "username",
password: "password",
},
body: current,
})
.then((response) => {
return res.status(200).send(response);
})
.catch((err) => {
return res.status(500).send(err);
});
});
I wrote an API that do some stuff, and I protect this using a jwt token.
This is the function for check the validity (checkAuth):
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization;
const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
req.userData = decoded;
next();
}
catch (error) {
return res.status(401).json({
message: 'Auth failed'
});
}
};
And I define the route of the API in this way:
router.post('/myAPI', checkAuth, MyAPIDefinition);
When I try to fetch the API, using an expired jwt I can't get the response of the checkAuth. This is my API call using await fetch:
const response = await fetch(`${API_URI_DEV}/myAPI`, {
method: 'POST',
body: JSON.stringify({encod: { content: data }}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'authorization': jwt
}
});
The content of response is undefined.
I need to be able to save the token returned by the POST request so I can decode it and send it back with my other requests. I can only console log the token but could find no way of saving it to a variable. How do I go about doing this? Am I thinking of this problem all wrong?
const request = require('request');
const options = { method: 'POST',
url: process.env.AUTH_URL,
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json',
api_key: process.env.API_KEY,
client_secret: process.env.CLIENT_SECRET,
client_id: process.env.CLIENT_ID },
body: { userName: process.env.USERNAME, userPassword: process.env.PASSWORD },
json: true };
async function authenticate(options) {
try{
console.log('inside try');
const reqToken = await request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body.token);
});
} catch(error) {
throw(error);
}
}
Either promisify the request or simply use axios which supports promise out of the box.
async function authenticate(options) {
try {
console.log("inside try");
const reqToken = await new Promise((res, rej) => {
request(options, function(error, response, body) {
if (error) rej(error);
res(body.token);
});
});
} catch (error) {
throw error;
}
}
OR using axios:
async function authenticate(options) {
try {
console.log("inside try");
const { data:{ token } } = await axios(options);
} catch (error) {
throw error;
}
}
i can't figure out what to place in exchange of the JSON.stringify syntax in the body parameter. It is returning a SyntaxError with a code of 800A03EA
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
body: JSON.stringify({
status: 'automated message to post'
})
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
Nothing. Instead, add
json: true to your options and don't attempt any stringification. request() will do the magic for you.
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
json: true,
body: {
status: 'automated message to post'
}
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
I'm have to call an API that use OAuth2 with Client Credentials.
I'm having some trouble to do it...
This is the code I produce (using request package) :
const credentials = {
client: {
id: 'MY_ID',
secret: 'My_PASSWORD'
},
auth: {
tokenHost: 'DOMAIN',
tokenPath: 'PATH',
scope: '',
grantType: "client_credentials"
}
};
var options = {
method: 'POST',
url: credentials.auth.tokenHost + credentials.auth.tokenPath,
headers: { 'content-type': 'application/json' },
body: {
grant_type: credentials.auth.grantType,
client_id: credentials.client.id,
client_secret: credentials.client.secret
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I have this error :
{ error: 'invalid_request',
error_description: 'Missing form parameter: grant_type' }
Maybe I'm missing something.
It would be very nice of you if you can help me to figure it out :)
PS : It works on Postman so my values are correct.