Vue,Express REST服务器和Google OAuth2

时间:2019-05-22 14:20:58

标签: node.js express vue.js passport.js google-oauth

我们在Vue中有一个前端,并有一个用ExpressJS和Passport用NodeJS编写的REST API服务器。我们正在尝试通过Vue应用程序使用Google OAuth2登录用户,并让用户在我们的REST服务器中注册,以便它可以请求用户个人资料来创建帐户并共享API密钥。最初的auth阶段似乎运作良好,但是当我们开始与后端进行交互时,它就会崩溃。

在客户端中,我们使用“ Quasar”和“ vue-google-oauth2”。在已注册的Quasar插件中,我们这样做:

import GoogleAuth from 'vue-google-oauth2';

export default ({ Vue }) => {
  const oauthOptions = {
    clientId: 'privateclientid.apps.googleusercontent.com',
    scope: 'profile email',
    prompt: 'select_account',
  };

  Vue.use(GoogleAuth, oauthOptions);
};

然后在登录视图中的按钮处理程序中:

this.$gAuth.getAuthCode()
  .then((authCode) => {
    console.log('handleGoogleLogin', authCode);
    return axios.post('http://localhost:3000/api/auth/google', {
      code: authCode,
      redirect_uri: 'postmessage',
    });
  })
  .catch((error) => {
    console.log(error);
  });
  },

在服务器上(在Typescript中):

// Preparing Google Strategy using passport-google-oauth20
passport.use(new GoogleStrategy({
    callbackURL: '../api/auth/google/redirect',
    clientID: config.googleApiClientId,
    clientSecret: config.googleApiClientSecret
}, (accessToken, refreshToken, profile, done) => {
    User.findOne({googleId: profile.id}).then((user) => {
        if(user){
            done(null, user);
        } else {
            done(null, false, profile);
        }
    }).catch(err => {
        done(err, false)
    });
}));

和端点处理程序:

function googleAuthenticate (req: Request, res: Response, next: NextFunction) {
    console.log('request: ', req.body);
    const redirect = 'http://localhost:8081/redirect/';
    const options = {
        session: false,
        scope: googleScopes,
        //successRedirect: redirect,
    }
    passport.authenticate('google', options, (err, user, profile) => {
        console.log('googleProfile');
    })(req, res, next);
};

最终发生的是,后端重定向到以'https://accounts.google.com/o/oauth2/v2/auth?response_type=code'开头的URL,然后以CORS错误结束:

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fgoogle%2Fredirect&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%09&client_id=privateclientid.apps.googleusercontent.com' (redirected from 'http://localhost:3000/api/auth/google') from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Vue应用程序在http://localhost:8081/#/login上运行,REST服务器在http://localhost:3000/api上运行

任何帮助将不胜感激-预先感谢。

0 个答案:

没有答案