【发布时间】:2018-09-27 22:43:20
【问题描述】:
上下文
我正在使用 Angular、Express 和 PassportJS 构建一个 无状态 应用程序,并希望使用他们的 Google 帐户对用户进行身份验证。在对用户进行身份验证后,我的目标是使用 JWT 令牌来拥有无状态应用程序。
Angular 2 侧面
点击 Google 登录按钮后,以下代码将在我的服务中执行:
login() {
return this.http.get('http://localhost:3000/api/auth/google');
}
快递方面
在 express 上,执行以下操作:
// 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 问题!
【问题讨论】:
-
这是 angular 的问题,节点检查请求的来源并抛出我认为的 cors 错误
标签: angular express oauth cors passport.js