Skip to content

Cell - OAuth2 客户端组件 ​

通过 OAuth 2.0 / OpenID Connect 提供商(GitHub、Google、Okta、Facebook 或任何其他)让用户登录,并获取访问令牌调用 API(支持客户端凭证、密码和刷新令牌授权类型)。集成到 @celljs/security:成功登录就是一个常规的安全登录。

bash
npm install @celljs/oauth2-client @celljs/security

通过提供商登录 ​

在 cell.yml 中注册客户端(服务端专用,与所有配置一样):

yaml
oauth2:
  client:
    registrations:
      github:
        clientId: "${env.GITHUB_CLIENT_ID}"
        clientSecret: "${env.GITHUB_CLIENT_SECRET}"
  • google、github、facebook 和 okta 有模板(本包 cell.yml 中的 registrationTemplates、providerTemplates),包含端点和作用域;Okta 和其他提供商需要在 oauth2.client.providers.<id> 下配置其 URL(authorizationUri、tokenUri、userInfoEndpoint.uri、userInfoEndpoint.userNameAttributeName、jwkSetUri、issuerUri)。
  • 一个注册包括 clientId、clientSecret、scopes、authorizationGrantType、clientAuthenticationMethod、redirectUri、provider(默认:其 id)和 clientName。
  • 把浏览器发送到 /oauth2/authorization/github(oauth2.client.authorizationRequestBaseUri)。提供商重定向回 /login/oauth2/code/github;默认重定向 URI 从 server.endpoint 构建,所以要设置 server.endpoint 为应用的公网 URL。
  • 使用 openid 作用域时,登录是 OpenID Connect:ID 令牌用提供商的 JWK 集验证(@celljs/oauth2-jose)。
  • 用户属性由 @celljs/security 的 security.userMapperRule.<provider> 映射。

用于 API 调用的令牌 ​

AuthorizedClientManager 用其声明的授权类型(client_credentials、password、refresh_token、authorization_code)为注册授权并保管令牌,在过期前 oauth2.client.clockSkew(60 秒)刷新。