如何在node js中在服务器端验证google auth token?

zyfwsgd6  于 2023-06-22  发布在  Node.js
关注(0)|答案(4)|浏览(181)

我的前端应用程序是使用gmail帐户 * 认证 *。
我在认证成功后取回id_token,作为Authorization Header作为 bearer token 发送。
例如http://localhost:4000/api
授权承载 token_id
nodejs服务器端,我调用下面的方法来验证token。

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");
    }
}

当我调用上面的方法时,我总是得到 Invalid 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发送到服务器端?Thru url,header?
  • 我做错了什么?

任何帮助是高度赞赏。

nsc4cvqm

nsc4cvqm1#

OAuth2Client.verifyIdToken从库源中获取一个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端点验证token:

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
  • 我是否以授权承载者身份发送id_token?还是仅限授权?
  • 如何将id_token发送到服务器端?Thru url,header?

您可以在Authorization头中发送JWT令牌,但它可能会导致使用multiple Authorization headers。最好对标记进行URL编码或将其嵌入正文中。Google example 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(...)
aiazj4mn

aiazj4mn2#

首先,不要使用Id_Token进行授权。它仅用于身份验证。使用访问令牌进行授权。使用下面的链接验证令牌。

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${access_token}
dzjeubhm

dzjeubhm3#

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

  • 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,则会失败

hsvhsicv

hsvhsicv4#

你现在可以使用firebase来验证google auth token。
首先创建一个名为firebase-config的文件,并保存你的firebase配置(从firebase设置中获取)。
导入这些:

import { initializeApp } from 'firebase-admin/app';
import { getAuth  } from 'firebase-admin/auth';
import { firebaseConfig } from 'PATH_TO_CONFIG_FILE';  //(importing of your config file that you had created)

初始化:

const defaultApp = initializeApp(firebaseConfig);

google token验证功能:

async verifyGoogleId(token) {
      const auth = getAuth(defaultApp);
      const firebaseUser = await auth.verifyIdToken(token);

      if (!firebaseUser) {
         throw new error();
      }
}

相关问题