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.