如何使用适用于 Web 服务器应用程序的 Google OAuth 2.0 将自定义声明添加到 Google ID_Token

Shr*_*a P 5 oauth oauth-2.0 jwt google-oauth

我们已经为 Web 服务器应用程序配置了 Google OAuth 2.0,如https://developers.google.com/identity/protocols/oauth2/web-server#httprest中所述。

  1. 使用代码,

    https://accounts.google.com/o/oauth2/v2/auth?范围=https%3A//www.googleapis.com/auth/drive.metadata.readonly&access_type=offline&include_granted_scopes=true&response_type=code&state=state_parameter_passthrough_value&redirect_uri=https%3A//oauth2.example.com/code&client_id=client_id。

  2. 使用 JWT,

    POST /token HTTP/1.1 主机:oauth2.googleapis.com 内容类型:application/x-www-form-urlencoded

    代码=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=your_client_id& client_secret=your_client_secret& redirect_uri=https%3A//oauth2.example.com/code& grant_type=authorization_code

现在我解码后的 id_token 看起来像,

{
  "alg": "RS256",
  "kid": "b63ee0be093d9bc312d958c9966d21f0c8f6bbbb",
  "typ": "JWT"
}.{
  "iss": "https://accounts.google.com",
  "azp": "640523414127-4eaptj129qb79v33pm0il71r4f506ts9.apps.googleusercontent.com",
  "aud": "640523414127-4eaptj129qb79v33pm0il71r4f506ts9.apps.googleusercontent.com",
  "sub": "118185565008542236388",
  "email": "mail_ID@gmail.com",
  "email_verified": true,
  "at_hash": "K_sS85PI2ptkOIrUoWcM7Q",
  "iat": 1595931406,
  "exp": 1595935006
}.[Signature]
Run Code Online (Sandbox Code Playgroud)

现在我如何添加自定义声明,以便上面的 id_token 包含我的新声明,例如,

“政策”:“读写”

最后解码后的 id_token 应该是这样的,

{
  "alg": "RS256",
  "kid": "b63ee0be093d9bc312d958c9966d21f0c8f6bbbb",
  "typ": "JWT"
}.{
  "iss": "https://accounts.google.com",
  "azp": "640523414127-4eaptj129qb79v33pm0il71r4f506ts9.apps.googleusercontent.com",
  "aud": "640523414127-4eaptj129qb79v33pm0il71r4f506ts9.apps.googleusercontent.com",
  "sub": "118185565008542236388",
  "email": "mail_ID@gmail.com",
  "email_verified": true,
  "at_hash": "K_sS85PI2ptkOIrUoWcM7Q",
  "iat": 1595931406,
  "exp": 1595935006,
**"policy": "readWrite"**
}.[Signature]
Run Code Online (Sandbox Code Playgroud)

小智 -2

也许会有帮助:

配置用户的自定义声明 (...) 开始之前 安装 Admin SDK。(...)

admin.auth().setCustomUserClaims(uid, {admin: true})
Run Code Online (Sandbox Code Playgroud)

https://cloud.google.com/identity-platform/docs/how-to-configure-custom-claims