如何在节点js中验证服务器端的google身份验证令牌?

时间:2017-02-23 01:30:27

标签: javascript node.js api google-signin google-authentication

我的前端应用程序使用gmail帐户进行身份验证

我在身份验证成功后检索 id_token ,并将其作为授权标头发送为 bearer token

E.g。 http://localhost:4000/api

授权承载 token_id

nodejs 服务器端,我调用以下方法来验证令牌。

exports.verifyUser = function(req, res, next) {
    var GoogleAuth = require('google-auth-library');
    var auth = new GoogleAuth();
    var client = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL);
    // check header or url parameters or post parameters for token
    var token = "";
    var tokenHeader = req.headers["authorization"];
    var items = tokenHeader.split(/[ ]+/);
    if (items.length > 1 && items[0].trim().toLowerCase() == "bearer") {
        token = items[1];
    }
    if (token) {
        var verifyToken = new Promise(function(resolve, reject) {
            client.verifyIdToken(
                token,
                config.passport.google.clientID,
                function(e, login) {
                    console.log(e);
                    if (login) {
                        var payload = login.getPayload();
                        var googleId = payload['sub'];
                        resolve(googleId);
                        next();
                    } else {
                        reject("invalid token");
                    }
                }
            )
        }).then(function(googleId) {
            res.send(googleId);
        }).catch(function(err) {
            res.send(err);
        })
    } else {
        res.send("Please pass token");
    }
}

当我调用上述方法时,我总是得到无效令牌响应,并出现以下错误。

Error: No pem found for envelope:     {"alg":"RS256","kid":"c1ab5857066442ea01a01601
850770676460a712"}
    at OAuth2Client.verifySignedJwtWithCerts (\node_modules\google-auth-libr
ary\lib\auth\oauth2client.js:518:13)
  • 这是验证令牌的正确方法吗?
  • 我是否将id_token作为授权持有者发送?或仅供授权使用?
  • 如何将id_token发送到服务器端?通过网址,标题?
  • 我做错了什么?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

OAuth2Client.verifyIdTokenlibrary source

中获取参数中的idToken
/**
 * Verify id token is token by checking the certs and audience
 * @param {string} idToken ID Token.
 * @param {(string|Array.<string>)} audience The audience to verify against the ID Token
 * @param {function=} callback Callback supplying GoogleLogin if successful
 */
OAuth2Client.prototype.verifyIdToken = function(idToken, audience, callback)

您已经传递了整个标头值bearer eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxYWI1OD U3MDY2NDQyZWEwMWEwMTYwMTg1MDc3MDY3NjQ2MGE3MTIifQ,因此您必须将标头值拆分为:

var authorization = req.headers["authorization"];
var items = authorization.split(/[ ]+/);

if (items.length > 1 && items[0].trim() == "Bearer") {
    var token = items[1];
    console.log(token);
    // verify token
}
  

这是验证令牌的正确方法吗?

是的,这是验证令牌的正确方法。对于调试,如果您有任何疑问或需要快速测试,还可以使用tokeninfo端点验证令牌:

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
  
      
  • 我是否将id_token作为授权持有者发送?或者是为了   只授权?
  •   
  • 如何将id_token发送到服务器端?直通   url,header?
  •   

您可以在授权标头中发送JWT令牌,但它可能会导致您使用multiple Authorization headers。最好对令牌进行URL编码或嵌入体内。您可以查看Google示例here

此外,Google还需要以下内容:

  • 必须通过HTTPS POST
  • 发送令牌
  • 必须验证令牌完整性

要优化代码,您还可以将Google auth对象移至应用根目录的app.js,而不是每次验证令牌时重新定义它。在app.js

var app = express();

var GoogleAuth = require('google-auth-library');
var auth = new GoogleAuth();
app.authClient = new auth.OAuth2(config.passport.google.clientID, config.passport.google.clientSecret, config.passport.google.callbackURL);

并在verifyUser中从req.app.authClient调用它:

req.app.authClient.verifyIdToken(...)

答案 1 :(得分:0)

今天终于找到答案了。 Firebase 工具会将原生 Google 连接到第三方登录令牌,然后再封装一层。此时获得的token不再是Google给我们的原始token。

  • A1:
    • 原始令牌:GoogleDesignInAccount Account = Task.getResult(ApiException.class);
    • Account.getidToken () // This is the original token
  • B1:
    • Firebase 令牌:FireBaseUser currentUser = Mauth.getCurrentUser ();
    • String token = currentUser.getIdToken(false).getResult().getToken();
  • A2:
    • Google 官方提供了验证令牌的方法
  • B2:
    • Firebase 官方提供了身份验证令牌方法

我们对上述四个数据点使用代号。如果需要在后台验证令牌的有效性,它们必须相互对应,A1到A2和B1到B2。如果你用A2验证B1,就会失败

相关问题