简体   繁体   English

如何验证客户端令牌并获取用户的电子邮件地址

[英]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:我想从 google auth 获得一个有效的电子邮件,并通过点击使用 google 按钮登录来注册我的用户,这样我就可以获得一个令牌,包括这样的用户电子邮件:

<!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?上面的代码获取token并将其发送到服务器,对吗?

Now on server side I can log the client token which we sent successfully using this console.log(token) :现在在服务器端,我可以使用这个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?问题是我们如何验证这个token是有效的,而不是由黑客发送的?

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:我现在的做法是将带有令牌的 post 请求发送到此 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 API 获取值的有效令牌


Google is using OpenID Connect(OAuth2.0) , which is very secure. Google 正在使用OpenID Connect(OAuth2.0) ,这是非常安全的。 The process, in a nutshell, for you简而言之,为您准备的过程

  1. Get redirected to google website on clicking login with Google单击“使用 Google 登录”后重定向到 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.如果您在 Google 控制台中创建的应用程序中的 redirect_uri 数组与重定向 url 匹配,那么在有效登录时,Google 会将您返回到重定向 url。
  4. The redirected uri has a query string for code.重定向的 uri 有一个代码查询字符串。 ie, code=*****code=*****
  5. In server, you use the code and client_secret(not needed in client) and exchange the code for access_token/id_token在服务器中,您使用代码和 client_secret(客户端不需要)并将code交换为 access_token/id_token

The token is generated so, and no other arbitrary token can access any Google resources using Google API.令牌是这样生成的,其他任意令牌都不能使用 Google API 访问任何 Google 资源。 It will return invalid token error它将返回无效令牌错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取带有Google访问令牌的电子邮件地址? - How to get email address with google access token? 如何在JavaScript中获取Liferay用户的电子邮件地址? - How to get Liferay user email address in JavaScript? 如何使用谷歌访问令牌获取用户电子邮件? - How to get user email with google access token? 如何在ColdFusion中验证新的电子邮件地址正确 - How to verify a new email address is correct in ColdFusion Firebase 身份验证网络:如何验证电子邮件地址 - Firebase authentication web: how to verify email address 无需创建用户帐户即可在Meteor中验证电子邮件地址 - Verify email address in Meteor without creating a user account 如何使用 nodejs 对电子邮件进行身份验证? 我收到一封关于用户提交的电子邮件的电子邮件,然后我点击我端的一个链接来验证这封电子邮件 - How can I authenticate an email using nodejs? I get an email for user submitted email, then I click a link on my end to verify this email 如何在加载 dom 之前验证用户令牌? - How to verify user token before the dom is loaded? 如何在创建用户之前验证电子邮件? - How to verify email before creating user? 回溯验证第二个电子邮件地址 - Lookback Verify Second Email Address
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM