使用带有Node.js的MERN堆栈/表达后端并响应客户端...
从事学校项目,并尝试合并Google的oAuth 2.0,以便学生可以使用学校提供的电子邮件登录。 Google的oAuth会在第一个请求周围返回包含Auth代码的查询字符串(我是通过按钮通过客户端从客户端执行的)。然后,您必须将此身份验证代码交换为刷新和身份验证令牌。我希望第一轮重定向通过服务器路由,因此我可以执行逻辑以仅允许登录我们的高中电子邮件帐户的域,这可以通过req.query.hd执行。根据该逻辑,在获取请求时,从Google重定向的服务器和用户的路由应匹配-我们可以在哪里执行我们的逻辑,对吗?
在那里,如果您不使用学校电子邮件域登录,我希望用户路由回客户端...,并显示一条消息,描述“您未使用正确的Google acc登录”。 ..如何实现?
下一步(如果电子邮件域是通行证),则在axios中进行放置请求应处理的交换,我不知道它的格式是否正确,但这是我要解决的下一个任务。如果有什么建议可以使流程更顺利,我将不胜感激!仅在高中和独立学习的情况下,如果代码看起来不正确,请随时让我知道。感谢所有帮助。
app.get("/signin/callback", (req, res, next) => {
//declare vars from query string api return for later use
console.log(req.query);
let hd = req.query.hd;
let authCode = req.query.code;
if(hd == 'guhsd.net') {
console.log('you are good to pass');
next();
} else {
console.log('you are not good to pass')
//REDIRECT TO REACT CLIENT ON PORT 3000 SAYING FAILED TO LOGIN
//BECAUSE YOU DID NOT SIGN IN WITH PROPER EMAIL ADDRESS
//THIS IS WHERE I NEED HELP/SUGGESTIONS TO REDIRECT BACK TO CLIENT
res.end;
};
res.send('making a post to exchange auth code for tokens')
axios.post('https://oauth2.googleapis.com/token', {
client_id: "a string",
client_secret: "a string",
code: authCode,
grant_type: "authorization_code",
//google handles redirect to client... react running on port:3000
redirect_uri: "http://localhost:3000"
});
});
答案 0 :(得分:0)
您的代码有几次失败,您正在调用next()
,然后继续调用res。
要重定向,您可以使用res.redirect,但首先要管理流量:
app.get("/signin/callback", (req, res, next) => {
//declare vars from query string api return for later use
console.log(req.query);
let hd = req.query.hd;
let authCode = req.query.code;
if(hd !== 'guhsd.net') {
console.log('you are not good to pass')
// The return is fot not continue executing the controller
return res.redirect(301, '/signing/?error=invalid_domain');
}
// Why you send it to the client?
// res.send('making a post to exchange auth code for tokens')
axios.post('https://oauth2.googleapis.com/token', {
client_id: "a string",
client_secret: "a string",
code: authCode,
grant_type: "authorization_code",
//google handles redirect to client... react running on port:3000
redirect_uri: "http://localhost:3000"
})
.then((response) => {
console.log('Your token must to be here');
console.log(response);
})
.catch((error) => {
console.log('Error happend');
next(error);
});
});