Tanguy Combe Tanguy Combe - 1 month ago 16
Node.js Question

Auth0 NodeJS Authentification Refused using npm request

I'm facing a problem, I tried to connect to Auth0 API to enable a strong identification on my WebApp.

For context :


  • Front-End : I'm using an angularJS front, and there I implemented the Lock Library to manage the Auth0 popup by following this webapp-specific tutorial.

  • Back-End : NodeJS & Express server, in order to verify the user's authentification, I use the npm lib "request" to call the Auth0 API.



If i understand well, a click on the auth0 widget sends a request to the specified endpoint URL, and it's received by the back-end:

app.get('/auth0CallbackURL', function (req, res) {
console.log(req.query.code);
var auth0code = req.query.code;
var client_secret = PROCESS.ENV.SERCRETID;
var domain = PROCESS.ENV.DOMAIN;
var client_id = PROCESS.ENV.CLIENTID;
var redirectUrl = PROCESS.ENV.REDIRECTURL;

var request = require('request'); // request-promise
var requestParams = {
url: 'https://mycompanydomain.auth0.com/oauth/token?client_id='+client_id+'&redirect_uri='+redirectUrl+'&client_secret='+client_secret+'&code='+auth0code+'&grant_type=authorization_code',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}


And then I call request() to get back the access_token and verify the authentification.

request(requestParams, function(err, data) {
if (err) {
console.log('Err:', err);
} else {
console.log('response body: ', data.body)
}


But the only result I get is :

{
"error": "access_denied"
"error_description": "Unauthorized"
}


At the begining i thougt it was my Auth0 configuration that's didn't allow my authentification, but it seems that there are OK.

Thanks in advance for your replies.

Answer

As per the page you linked, you need to pass the following information:

client_id=YOUR_CLIENT_ID
&redirect_uri=https://YOUR_APP/callback
&client_secret=YOUR_CLIENT_SECRET
&code=AUTHORIZATION_CODE
&grant_type=authorization_code

in the request body and with a content type of application/x-www-form-urlencoded.

You're setting the content type correctly, but then are passing the data in the URL query component and instead you need to pass it the POST request body.

Using request package you should do the following:

var requestParams = {
    url: 'https://mycompanydomain.auth0.com/oauth/token',
    method: 'POST',
    body: 'client_id=' + client_id + 
        '&redirect_uri=' + redirectUrl + 
        '&client_secret=' + client_secret + 
        '&code=' + auth0code + 
        '&grant_type=authorization_code',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}