尝试通过Google +

时间:2019-06-19 17:12:17

标签: javascript node.js authentication google-authentication google-plus-signin

我正在通过遵循本文https://medium.com/@jackrobertscott/how-to-use-google-auth-api-with-node-js-888304f7e3a0

来实现简单的google唱歌

具有google身份验证的页面已加载,我可以选择要登录的帐户,但是选择该帐户后,它几乎无休止地加载然后输出

  

(节点:8548)UnhandledPromiseRejection警告:错误:invalid_grant

     

在Gaxios.request(C:\ Users \ misha \ Documents \ JavaScriptProjects \ spa \ node_modules \ gaxios \ build \ src \ gaxios.js:70:23)

     

在process._tickCallback(内部/process/next_tick.js:68:7)

我正在使用express.js作为后端框架

这是我的服务器代码(我只提供了必要的代码部分):

server-dev.js

import googleAuthUtil from './utils/google-auth-util';
app.get('/api/v1/googlelogin',(req,res) => {
 res.send(googleAuthUtil.urlGoogle());
});
app.get('/googleAuth',(req,res) => {
  console.log(googleAuthUtil.getGoogleAccountFromCode(req.query.code));
});

./ utils / google-auth-util.js

import {google} from 'googleapis';

const googleConfig = {
  clientId: '21263739003-l210171qijqppm4u0a0uc3b1rndfq1gj.apps.googleusercontent.com', 
  clientSecret: 'yWaL8LVUHh-39VCZbvNq0Ff8', 
  redirect: 'http://localhost:8080/googleAuth', 
};

const defaultScope = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/userinfo.email',
];


function createConnection() {
  return new google.auth.OAuth2(
    googleConfig.clientId,
    googleConfig.clientSecret,
    googleConfig.redirect
  );
}

function getConnectionUrl(auth) {
  return auth.generateAuthUrl({
    access_type: 'offline',
    prompt: 'consent',
    scope: defaultScope
  });
}

function getGooglePlusApi(auth) {
  return google.plus({version: 'v1', auth});
}


const googleUtils = {

  urlGoogle: function () {
    const auth = createConnection();
    const url = getConnectionUrl(auth);
    return url;
  },

  getGoogleAccountFromCode: async function (code) {
    const auth = createConnection();
    const data = await auth.getToken(code);
    const tokens = data.tokens;
    auth.setCredentials(tokens);
    const plus = getGooglePlusApi(auth);
    const me = await plus.people.get({userId: 'me'});
    const userGoogleId = me.data.id;
    const userGoogleEmail = me.data.emails && me.data.emails.length && me.data.emails[0].value;
    return {
      id: userGoogleId,
      email: userGoogleEmail,
      tokens: tokens,
    };
  }
};

export default googleUtils;

我的项目是一个单页应用程序,因此我在js文件的帮助下在客户端渲染页面。

这是我的前端代码(我只提供了必要的代码部分):

homepage.js

async function getGoogleLoginUrl(){
  const response = await fetch('/api/v1/googlelogin');
  const text = await response.text();
  return text;
}

let homePage = {
  render: async function () {
    let posts = await getPosts();
    let loginUrl = await getGoogleLoginUrl();
    console.log(posts[0].id);
    console.log(posts[0]._id);
    return `<a href="${loginUrl}">Login with google</a>`;
    //my home page is basically a blank screen with a link to google login
  }
};

正如我之前说的,大多数逻辑工作正常,并且仅在very end崩溃,当我选择要用于登录的帐户时

0 个答案:

没有答案