javascript - 我可以使用 jwcrypto 来验证 Google 生成的 OAuth2 id_token 吗?

标签 javascript node.js security oauth google-authentication

以这个问题的工作为基础:What is the proper way to validate google granted OAuth tokens in a node.js server?

我可以使用 jwcrypto 吗?用于在 node.js 服务器中验证 Google OAuth2 token 的库?我有 Google 提供的 857 字节 token ,它使用位于 https://www.googleapis.com/oauth2/v1/tokeninfo?id_token= 的 Google 网络端点进行验证。理论上我可以使用 token 加上可用的 Google 证书 here它们看起来像这样:

{
859c1234d08e008cc261ff11de5f8da1b8c4d490: "-----BEGIN CERTIFICATE----- <stuff> -----END CERTIFICATE----- ",
ad2a50cb70c5da789ee26d05b8f621a99e81202e: "-----BEGIN CERTIFICATE----- <stuff> -----END CERTIFICATE----- "
}

到目前为止,我什至无法使用 loadPublicKey 方法将 key 加载到 jwcrypto 中。大概一旦我开始工作,我就可以调用验证方法。网上有这方面的工作示例吗?

最佳答案

我刚刚添加了一个新的 npm 模块,用于解码和验证 Google 的 id_token。您可以在此处找到代码:https://github.com/gmelika/google-id-token

用法相当简单:

var googleIdToken = require('google-id-token');
var parser = new googleIdToken({ getKeys: getGoogleCerts });
parser.decode(sampleGoogleIDToken, function(err, token) {
    if(err) {
        console.log("error while parsing the google token: " + err);
    } else {
        console.log("parsed id_token is:\n" + JSON.stringify(token));
    }
});

上面提到的 getGoogleCerts 函数是用户提供的函数,它会根据提供的 key 返回适当的 Google 证书。一个非常基本的例子是:

var request = require('request');
function getGoogleCerts(kid, callback) {
    request({uri: 'https://www.googleapis.com/oauth2/v1/certs'}, function(err, response, body){
        if(err && response.statusCode !== 200) {
            err = err || "error while retrieving the google certs";
            console.log(err);
            callback(err, {})
        } else {
            var keys = JSON.parse(body);
            callback(null, keys[kid]);
        }
    });
}

显然,您可能希望在其中添加缓存。随意使用您最喜欢的缓存机制来做到这一点。

希望对您有所帮助。

关于javascript - 我可以使用 jwcrypto 来验证 Google 生成的 OAuth2 id_token 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16347907/

相关文章:

javascript - 如何使用 Javascript 捕获表单自动完成事件?

javascript - 如何使用 Angular JavaScript 从(php 编码的 json)获取值?

php - 使用crypt()和password_hash()函数加密后密码不匹配

javascript - express.json() 是将Request对象识别为JSON对象?

php - 暴露用户ID有危险吗?

java - 安全!我想知道是否有办法让我的程序更安全(新手程序员)

javascript - ember js中push和pushObject的区别

javascript - 在 jQuery 中获取全局样式表的值

node.js - 模块.js :338 throw err in node. js

node.js - typescript 错误找不到名称 'require'。 ionic 3