简体   繁体   中英

How to use Google oAuth with Node.js backend and Angular frontend?

I am using Node.js on backend and creates a token for a user each time logins. angularx-social-login package makes it very easy to integrate Google OAuth with Angular but how to use it with API? After successful login the Google returns user information with token. I was thinking to send this information to backend and login the user but for that I need to create a route which accepts email address and logins user. And this will return JWT token which is not secure. By secure I mean, anyone can access the route without Google Authentication and generate token.

I am looking for ideas how developers achieved this.

I found google-auth-library client package for Node.js managed by Google.

Here is the follow:

  1. Login user with Angular
  2. Send the idToken to backend
  3. Validate token and response to Angular

Node.js:

exports.googleLogin = function(req, res, next) {
  //verify the token using google client
  return googleClient
    .verifyIdToken({
      idToken: req.body.token,
      audience: config.google.clientID
    })
    .then(login => {
      //if verification is ok, google returns a jwt
      var payload = login.getPayload();
      var userid = payload['sub'];

      //check if the jwt is issued for our client
      var audience = payload.aud;
      if (audience !== config.google.clientID) {
        throw new Error(
          'error while authenticating google user: audience mismatch: wanted [' +
            config.google.clientID +
            '] but was [' +
            audience +
            ']'
        );
      }
      //promise the creation of a user
      return {
        name: payload['name'], //profile name
        pic: payload['picture'], //profile pic
        id: payload['sub'], //google id
        email_verified: payload['email_verified'],
        email: payload['email']
      };
    })
    .then(user => {
      return res.status(200).json(user);
    })
    .catch(err => {
      //throw an error if something gos wrong
      throw new Error(
        'error while authenticating google user: ' + JSON.stringify(err)
      );
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM