Here is my code which use Node.js(express):
router.get(
'/login',
passport.authenticate('auth0', {
clientID: env.AUTH0_CLIENT_ID,
domain: env.AUTH0_DOMAIN,
redirectUri: env.AUTH0_CALLBACK_URL,
audience: 'https://' + env.AUTH0_DOMAIN + '/userinfo',
responseType: 'code',
scope: 'openid'
}),
function(req, res) {
res.redirect('/');
}
);
// Perform session logout and redirect to homepage
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
// Perform the final stage of authentication and redirect to '/user'
router.get(
'/callback',
passport.authenticate('auth0', {
failureRedirect: '/'
}),
function(req, res) {
// res.redirect(req.session.returnTo || '/user');
let code =req.query.code;
if (code){
console.log("callback",code);
res.redirect(req.session.returnTo || '/user');
getToken(code,function (result,err) {
if (err){
console.log(err);
return;
}
console.log(result);
result.on('data',function(chunk){
console.log('数据片段分隔-----------------------\r\n');
console.log(chunk);
});
});
}
}
);
function getToken(code,callback) {
let options = { method: 'POST',
url: 'https://liberty-peter.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body:
{
grant_type: 'authorization_code',
client_id: 'Client_id',
client_secret: 'Client_secret',
code: code,
redirect_uri: 'http://localhost:3000/callback'
},
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
}
router.get('/user',function (req, res) {
res.send("response success");
});
In the code,I will open the url(http://localhost/login),input my username and password and click the login button,after login success,I will use the code from the params of callback url to call url(https://liberty-peter.auth0.com/oauth/token) to obtain the access_token.
However,it always returns a error response:
{ error: 'invalid_grant',
error_description: 'Invalid authorization code' }
I’m new to auth0 and fetch this problem for a whole day.I do not know what the problem is.
I would really appreciate it if someone can help me ive been struggling for 1 day now.
Thanks alot for taking your time and reading my post!