角度/快递/护照 - 通过谷歌身份验证:没有"访问控制-允许-来源"



>上下文

我正在使用Angular,Express和PassportJS构建一个无状态应用程序,并希望使用他们的Google帐户对用户进行身份验证。对用户进行身份验证后,我的目标是使用 JWT 令牌来拥有无状态应用程序。

角度 2 面

单击Google登录按钮后,将在我的服务中执行以下代码:

login() {
return this.http.get('http://localhost:3000/api/auth/google');
}

快递侧

在快速时,将执行以下内容:

// This gets executed first after clicking the sign in using Google button.
router.get('/api/auth/google', passport.authenticate('google', {
session: false,
scope: ['profile', 'email']
}));
// Google sends me back here (callback).
passport.use(new GoogleStrategy({
clientID: 'omitted',
clientSecret: 'omitted',
callbackURL: '/api/auth/google/callback'
}, function (accessToken, refreshToken, profile, cb) {
// Here, I obtain the profile and create a JWT token which I send back to the user.
let jwtToken = generateToken(); // Code omitted for simplicity.
cb(null, jwtToken); // assume success
}
));
// After creating a JWT token, this will get executed. 
router.get('/api/auth/google/callback', (req, res, next) => {
passport.authenticate('google', (err, jwtToken) => {
res.status(201).json(jwtToken);
})(req, res);
});

错误:

单击"使用 Google 登录"按钮(即从 Angular 发出get请求)后,我收到以下错误:

Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=(long_string_here): No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我试过什么

我在 Angular 和 React 应用程序上看到了类似的问题,虽然有答案(我已经尝试过),但没有"公认的答案"可以真正解决这个问题。我真的很震惊为什么这是一个这样的问题:

奇怪的部分是:如果我直接拨打window.location.href = http://localhost:3000/api/auth/google而不是发出get请求,它工作正常。但是,问题是我无法获得我的 JWT 令牌,因为我被完全重定向了。

我还尝试在后端以许多不同的方式启用 CORS,并允许各种来源。这不会改变任何东西。

这里需要注意的是,我的 Angular 应用程序在端口4200上运行,我的 Express 应用程序在端口3000上运行。但是,即使我编译了我的 Angular 项目并将其放在 Express 的公共文件夹中并为其提供服务,我仍然会遇到相同的 CORS 问题!

从登录中调用,

flogin(){
window.open('/auth/facebook',"mywindow","location=1,status=1,scrollbars=1, width=800,height=800");
let listener = window.addEventListener('message', (message) => {
//message will contain facebook user and details
});
}

在服务器中, 我希望你已经护照Facebook-Stratagy工作

app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email'] }));

app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/auth/fail' }),
function(req, res) {
var responseHTML = '<html><head><title>Main</title></head><body></body><script>res = %value%; window.opener.postMessage(res, "*");window.close();</script></html>'
responseHTML = responseHTML.replace('%value%', JSON.stringify({
user: req.user
}));
res.status(200).send(responseHTML);

});

相关内容

最新更新