ID token和access token有什么区别,如何使用JWT实现?

What is the difference between ID token and access token, and how to implment them using JWT?

所以我一直在阅读 ID 令牌和访问令牌之间的区别是为了授权。 ID token不知道怎么实现,应该是JWT。

我一直在实施的访问令牌如下所示:

const accountCredentials = {
    username: account.username,
    accountId: account.accountId,
    grant_type: "password"
}

const token = jwt.sign(accountCredentials, config.JWT_KEY, { expiresIn: "1h" })

所以我想知道,ID 令牌应该包含什么以及如何按照 openID 连接规范的描述实现它。对不起,这听起来可能很愚蠢,但我真的不明白文档。

ID 令牌是一种允许您的应用识别用户的令牌。它始终是一个 JWT,其内容在 OIDC 文档的这一部分进行了描述:https://openid.net/specs/openid-connect-core-1_0.html#IDToken 因此,要获得有效的 ID 令牌,您需要一个至少包含以下声明的 JWT:isssubaudexpiat。您可以查看规范,了解每个声明应包含的内容。此外,ID 令牌必须至少经过签名(也可以加密)。

在你的代码中你会有这样的东西:

const accountCredentials = {
    iss: '...',
    sub: account.username,
    aud: '...',
    iat: now()
}

const token = jwt.sign(accountCredentials, config.JWT_KEY, { expiresIn: "1h" })

请注意,OpenID Connect 规范仅指定授权码、隐式和混合流。使用密码授予类型不是 OIDC 标准的一部分。