我已经使用Google身份验证设置了angular / nodejs(express)应用程序,但是每当我通过angular应用程序请求google oauth时,都会引发cors错误,但是如果我直接从浏览器中请求,它将按预期运行。
后端在端口3000上运行,而angular在4200上运行。
我正在使用cors
包来允许server.js中的所有cors请求:
app.use(passport.initialize());
// Passport Config
require('./config/passport')(passport);
// Allowing all cors requests
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', usersRouter);
app.use('/auth', authRouter);
护照配置:
passport.use(
new GoogleStrategy(
keys,
(token, refreshToken, profile, done) => {
process.nextTick(() => {
User.findOne({ email: email })
.then(user => {
if (user) {
return done(null, user);
}
})
.catch(err => console.log(err));
});
}
)
);
这是google身份验证路由:
router.get('/google', passport.authenticate('google', {
scope: ['profile', 'email'],
session: false
}),
(req, res) => {
// Create JWT payload
const payload = {
id: req.user.id,
email: req.user.email
};
jwt.sign(payload, secret, expires, (err, token) => {
res.json(token);
});
}
);
这是角度要求:
googleAuth() {
return this.http.get<any>('http://localhost:3000/auth/google').pipe(
map(user => {
if (user) {
localStorage.setItem(
'currentUser',
JSON.stringify(user)
);
}
return user;
})
);
}
Chrome控制台中的错误:
Failed to load "https://accounts.google.com/o/oauth2/v2/auth?response_type=code...": No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
我还授权了Google开发者控制台中的JavaScript起源: origins
我对angular和nodejs还是很陌生,我已经阅读了所有类似的问题,但是找不到解决此问题的方法。
答案 0 :(得分:0)
尝试这种直接调用URL的方法:(请原谅,如果我在语法上错过了一些内容,但基本上是这样)
googleAuth(){
window.open('/google',"mywindow","location=1,status=1,scrollbars=1, width=800,height=800");
let listener = window.addEventListener('message', (message) => {
//message will contain google user and details
});
}
在服务器中,我假设设置了护照策略,现在
router.get('/google', passport.authenticate('google', {
scope: ['profile', 'email'],
session: false } ))
router.get('/google/callback',
passport.authenticate('google', { 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);
});