我正在使用 expressJs 和护照进行身份验证。我正在使用 Google Oauth2.0 通过标准 Passport GoogleStrategy 登录。在客户端,我使用 axios 向服务器发送登录请求。我的登录路线是:
router.get(
"/google",
passport.authenticate("google", { scope: ["profile", "email"] }));
router.get(
"/google/callback",
passport.authenticate("google", { failureRedirect: "/"}),
function(req, res) {
const token = jwt.sign({id: req.user.id}, configAuth.secretKey);
console.log("generated token: ", token);
res.json({success: true, token: 'bearer ' + token});
}
);
我正在使用回调中的用户信息来生成我想要发送给客户端的 JWT。
在客户端,我使用 axios 发送请求并获取 JWT 并将其存储在 localstore 中。
axios.get('http://localhost:3001/google')
.then((result) => {
console.log("result", result);
localStorage.setItem('jwtToken', result.data.token);
})
.catch((error) => {
// if(error.response.status === 401) {
// this.setState({ message: 'Login failed. Username or password not match' });
// }
console.log("Login error", error);
});
但是 Axios 不会等待重定向发生并返回一个带有 Loading... 消息的 HTML 文档。如果您尝试在浏览器中访问 API,它会返回所需的 JSON 对象。有没有办法等待重定向。我应该使用另一个库来发送登录请求吗?
我尝试将令牌作为 url 参数发送
res.redirect()
但是客户端和服务器位于不同的端口,所以它不起作用。还有另一种方法吗?