Angular / Express / Passport - 使用Google进行身份验证:无'访问控制 - 允许 - 来源

时间:2018-04-17 20:32:20

标签: angular express oauth cors passport.js

上下文

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

Angular 2 side

点击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问题!

1 个答案:

答案 0 :(得分:5)

从登录中调用,

Component Inspector

在服务器中, 我希望你有护照facebook-stratagy工作

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
});

}
相关问题