3

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.

1

1 Answer 1

6

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)
      );
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.