简体   繁体   中英

How to verify the client token and get the email address of the user

I want to get a valid email from google auth and signup my user simply by clicking sign in with google button so I can get a token including user email like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-signin-client_id" content="203772907695-qd52ou2r1bcsht8f515lh63cpqaateq2.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <title>Login</title>
</head>
<body>

    <div class="g-signin2" data-onsuccess="onSignIn"></div>

    <script>
    function onSignIn(googleUser) {

        var id_token = googleUser.getAuthResponse().id_token;
        console.log(id_token);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/login');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function() {
            console.log('Signed in as: ' + xhr.responseText);
            if(xhr.responseText == 'success'){
                signOut();
                location.assign('/profile')
            }
        };
        xhr.send(JSON.stringify({token : id_token}));
      }
    </script>
    
</body>
</html>

The code above gets the token and simply send it to the server right?

Now on server side I can log the client token which we sent successfully using this console.log(token) :

// Google Auth
const {OAuth2Client} = require('google-auth-library');
const CLIENT_ID = '203772907695-qd52ou2r1bcsht8f515lh63cpqaateq2.apps.googleusercontent.com'
const client = new OAuth2Client(CLIENT_ID);

app.post('/login', (req,res)=>{
    let token = req.body.token;
    console.log(token); // gets the token successfully
    // then we should verify that this token is valid not one sent by a hacker right?

})

The question is how we can verify that this token is valid and not one sent by a hacker?

Because as you can see a hacker can simply do what we did in the client side and send us a token just like our token...

The way I'm doing it right now is to send a post request with the token to this url:

const response = await axios.post(`https://oauth2.googleapis.com/tokeninfo?id_token=${token}`);
const email = response.data.email;

But this is not verifying anything anyone can send that token and get the similar result...

I want to securely get the user email by verifying the token which is send by the user.

You can simplyread the documentation which explains how to do that. This is the example they show:

const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  const userid = payload['sub'];
  // If request specified a G Suite domain:
  // const domain = payload['hd'];
}
verify().catch(console.error);

The question is how we can verify that this token is valid and not one sent by a hacker?

A hacker cannot generate a valid token that will fetch the values from Google API.


Google is using OpenID Connect(OAuth2.0) , which is very secure. The process, in a nutshell, for you

  1. Get redirected to google website on clicking login with Google
  2. You login there after providing requested permissions
  3. Google, on a valid login, returns you back to the redirect url, if it matches the redirect_uri array in the app you created in google console.
  4. The redirected uri has a query string for code. ie, code=*****
  5. In server, you use the code and client_secret(not needed in client) and exchange the code for access_token/id_token

The token is generated so, and no other arbitrary token can access any Google resources using Google API. It will return invalid token error

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