跳到主内容

OAuth 2.0

Casdoor 是一个 OAuth 2.0 授权服务器。本页介绍如何通过每种授权类型获取访问令牌、验证令牌以及使用令牌。如果您不想自己调用端点,可以使用 Casdoor SDK 或 标准 OIDC 客户端。

端点​

EndpointURL
Authorizationhttps://<casdoor-host>/login/oauth/authorize
Tokenhttps://<casdoor-host>/api/login/oauth/access_token
Refresh tokenhttps://<casdoor-host>/api/login/oauth/refresh_token
Token introspectionhttps://<casdoor-host>/api/login/oauth/introspect
Token revocationhttps://<casdoor-host>/api/login/oauth/revoke
UserInfohttps://<casdoor-host>/api/userinfo

在示例中,ClientId 和 ClientSecret 是 Casdoor 应用 的 Client ID 和 Client secret。

支持的授权类型​

授权类型RFC用例
授权码RFC 6749 §4.1默认;带有后端的Web/移动应用。默认启用。
t隐式RFC 6749 §4.2仅前端应用,无后端。
资源所有者密码RFC 6749 §4.3无前端重定向的应用程序;用户凭据直接发送。
客户端凭证RFC 6749 §4.4服务间调用,无需用户参与。
刷新令牌RFC 6749 §6无需重新认证即可续订访问令牌。
设备授权RFC 8628输入受限或无浏览器的设备
令牌交换RFC 8693用现有令牌交换具有不同范围或受众的令牌。
JWT持有者RFC 7523使用签名的JWT断言而非客户端密钥进行服务身份验证。
验证码Casdoor 扩展通过短信或电子邮件发送的代码来登录(和注册)用户的原生应用。
手机一键登录Casdoor 扩展通过阿里云 PNVS 使用设备电话号码来登录(和注册)用户的原生应用。

授权码模式默认启用。请在应用的编辑页面中,在 Grant types 下启用其他授权类型。

Grant types setting of the application

授权码许可​

此授权类型适用于通过浏览器登录用户的应用程序。这是推荐的授权类型。

  1. 将用户重定向到授权端点:

    https://<CASDOOR_HOST>/login/oauth/authorize?
    client_id=CLIENT_ID&
    redirect_uri=REDIRECT_URI&
    response_type=code&
    scope=openid&
    state=STATE
  2. 用户登录。Casdoor 会将浏览器重定向到您的重定向 URL,并附带一个授权码:

    https://REDIRECT_URI?code=CODE&state=STATE&iss=ISSUER

    iss 是 Casdoor 的签发者 URL,由 RFC 9207 定义。请将其与发现文档中的 issuer 进行比较,以确保响应来自您发送用户前往的 Casdoor 服务器。Casdoor 会在每个授权响应以及发回给重定向 URL 的每个错误中添加 iss,并且发现文档通过 "authorization_response_iss_parameter_supported": true 来宣布支持此功能。

  3. 用代码交换令牌。向令牌端点发送一个 POST 请求:

    https://<CASDOOR_HOST>/api/login/oauth/access_token

    请求体如下:

    {
    "grant_type": "authorization_code",
    "client_id": ClientId,
    "client_secret": ClientSecret,
    "code": Code,
    }
  4. 从响应中读取令牌:

    {
    "access_token": "eyJhb...",
    "id_token": "eyJhb...",
    "refresh_token": "eyJhb...",
    "token_type": "Bearer",
    "expires_in": 10080,
    "scope": "openid"
    }

授权码有效期为 5 分钟且仅能使用一次。第二次交换同一代码会失败,返回 invalid_grant 错误,描述为 authorization code has been used for token: [...]。

令牌端点和刷新令牌端点的响应携带 Cache-Control: no-store 和 Pragma: no-cache 标头,以确保缓存不会保留令牌。

作用域​

使用授权 URL 的 scope 参数请求范围。它们决定了令牌和 UserInfo 端点返回哪些用户字段。

作用域描述
openid(默认)sub、iss、aud
profilename、displayName、avatar
email电子邮件地址
address地址(OIDC 对象在JWT 标准中;请参阅OIDC 地址声明)
phone电话号码

多个范围之间用 %20 分隔:

https://<CASDOOR_HOST>/login/oauth/authorize?
client_id=...&
scope=openid%20email

有关每个范围背后的声明,请参阅 OpenID Connect 规范。

PKCE​

Casdoor 支持 Code Exchange 证明密钥 (PKCE),它保护公共客户端(如移动应用和单页应用)的授权码。

  1. 生成一个长度为 43 到 128 个字符的随机代码验证器。

  2. 计算代码挑战:即验证器的 Base64-URL 编码 SHA-256 哈希值。

  3. 在授权 URL 中添加两个参数:

    &code_challenge_method=S256&code_challenge=YOUR_CHALLENGE
  4. 在令牌请求中添加 code_verifier 参数,其值为原始验证器。

使用 PKCE 时,client_secret 在令牌请求中是可选的。如果您发送了它,则必须正确。

备注

当 Casdoor 自身在需要 PKCE 的外部 OAuth 提供商(如 Twitter 或启用了 PKCE 的自定义提供商)处为用户登录时,Casdoor 会为每次流程生成代码验证器。您无需为该部分实现 PKCE。

将令牌绑定到一个服务​

如果您的应用程序调用多个后端服务,您可以将令牌绑定到其中一个服务,以便为一个服务签发的令牌不能用于另一个服务。Casdoor 为此支持 资源指示符 (RFC 8707)。

  1. 在授权 URL 中添加 resource 参数,其值为标识该服务的绝对 URI:

    https://<CASDOOR_HOST>/login/oauth/authorize?
    client_id=CLIENT_ID&
    redirect_uri=REDIRECT_URI&
    response_type=code&
    scope=openid&
    state=STATE&
    resource=https://api.example.com
  2. 在令牌请求中发送相同的 resource:

    {
    "grant_type": "authorization_code",
    "client_id": ClientId,
    "client_secret": ClientSecret,
    "code": Code,
    "resource": "https://api.example.com"
    }

此时访问令牌的 aud(受众)声明将是资源 URI,而不是客户端 ID。服务通过检查 aud 来验证令牌是否为其签发。两次请求中 resource 的值必须完全相同。

Casdoor 在交互式登录过程中保留 resource 参数。如果用户必须输入密码、完成多因素身份验证 (MFA)、使用 WebAuthn 或批准同意页面,该参数将在重定向过程中保持不变。当 Casdoor 使用现有会话自动登录用户时,该参数也会被保留。

当您刷新令牌时,新的访问令牌保留原始授权的 aud。您可以在刷新请求中重复 resource,作为查询参数或请求体的字段。如果这样做,它必须与原始授权中的值相同。否则,Casdoor 将返回 invalid_grant,描述为 resource parameter does not match the original grant。

使用提供商提示跳过登录页面​

要将用户直接发送到某个 OAuth 提供商,而不显示 Casdoor 登录页面,请在授权 URL 中添加 provider_hint=<provider-name>:

https://<CASDOOR_HOST>/login/oauth/authorize?
client_id=CLIENT_ID&
redirect_uri=REDIRECT_URI&
response_type=code&
scope=openid&
state=STATE&
provider_hint=github

然后 Casdoor 提供一个小的重定向页面,不加载完整的前端,并将用户发送到提供商。这缩短了慢速设备和连接上的重定向时间。

在授权流程中注册​

在授权流程中创建账户的用户,一旦注册完成,就会像登录后一样被重定向到您的重定向 URL 并附带授权码。Casdoor 在注册过程中保留授权参数,例如 client_id、response_type 和 redirect_uri。您的应用程序无需为此进行任何更改。

控制登录提示​

默认情况下,已有 Casdoor 会话的用户可以在不重新输入凭据的情况下登录。在授权 URL 中添加 OpenID Connect 参数 prompt 和 max_age 以更改此行为:

ParameterEffect
prompt=loginThe user must enter credentials again, even with an existing session
max_age=<seconds>如果用户上次输入凭据的时间超过 <seconds> 秒前,或者 Casdoor 不知道他们何时输入的,用户必须重新输入凭据
prompt=noneCasdoor shows no page. It signs the user in with the existing session, or sends an error back to the redirect URL

prompt 接受以空格分隔的值列表。当现有会话不满足 prompt=login 或 max_age 时,使用该会话登录将失败,返回 login_required 错误,消息为 Please sign in again。用户输入凭据的时间位于 ID 令牌的 auth_time 声明中。

使用 prompt=none 来检查(例如从隐藏的 iframe 中)用户是否仍处于登录状态。然后 Casdoor 跳过对单个提供商的自动重定向,并以与成功响应相同的方式回答,包含 state 和 iss,以及以下错误之一:

ErrorReason
login_requiredNo Casdoor session, the user of the session isn't in the organization of the application, or the session doesn't satisfy max_age
consent_requiredThe user must approve the consent page first
interaction_requiredThe user must update the password, set up or complete MFA, select a plan, or fill in the prompt page first
access_deniedThe sign-in failed for another reason. error_description says why
server_errorThe request to Casdoor failed

隐式授权​

仅将此授权用于没有后端的应用程序。更推荐使用带有 PKCE 的授权码模式。

  1. 在应用的 Grant types 中,开启 Token 以返回访问令牌,开启 ID Token 以返回 ID 令牌,或两者都开启。

  2. 将用户重定向至:

    https://<CASDOOR_HOST>/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=token&scope=openid&state=STATE
  3. 用户登录后,Casdoor 会将浏览器重定向到:

    https://REDIRECT_URI#access_token=ACCESS_TOKEN&token_type=Bearer&state=STATE&iss=ISSUER

response_type 可以是 token、id_token 或 id_token token。授权端点从不返回刷新令牌。如果响应类型所需的授予类型未开启,Casdoor 会显示 Grant_type: token is not supported in this application(或 id_token)。

当 scope 包含 openid 且响应包含 ID 令牌时,请发送 nonce 参数。Casdoor 会将其复制到 ID 令牌中,并在缺少该参数时拒绝请求:The nonce parameter is required for this response type。

注意事项

令牌端点的隐式授予(使用用户名和密码的 grant_type=token)需要具有本地密码的用户。仅通过外部提供商创建且没有本地密码的用户无法使用此功能,并会收到 invalid_grant 错误。与密码授予相同的规则适用。对于这些用户,请使用授权码授予。

混合流程​

在 OpenID Connect 混合流程中,授权端点返回授权码以及令牌。前端可以立即使用这些令牌,而后端则像授权码授予那样交换代码。

response_type 是 code、token 和 id_token 的空格分隔组合。混合值包括:

response_typeThe authorization endpoint returns
code id_tokencode and id_token
code tokencode and access_token
code token id_tokencode、access_token 和 id_token
  1. 在应用的 Grant types 中,对于包含 token 的响应类型开启 Token,对于包含 id_token 的响应类型开启 ID Token。

  2. 使用响应类型和 nonce 将用户重定向到授权端点:

    https://<CASDOOR_HOST>/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code%20id_token&scope=openid&state=STATE&nonce=NONCE

    当 scope 包含 openid 且响应类型包含 id_token,或者响应类型为 code token 时,必须提供 nonce。

  3. 用户登录后,Casdoor 会将浏览器重定向到您的重定向 URL。除非您指定了其他响应模式,否则值位于片段中。

  4. 在令牌端点交换代码。只有此交换操作会返回刷新令牌。

ID 令牌携带 OpenID Connect 规范中的以下声明:

声明When it's present
auth_timeWhen Casdoor knows the time at which the user last entered credentials
at_hashWhen the ID token comes with an access token, and in the ID token of the authorization code grant
c_hashWhen the ID token comes with an authorization code

at_hash 和 c_hash 使用 SHA-256,或者当应用的 Token signing method 以 384 或 512 结尾时使用 SHA-384 或 SHA-512。请按照 OpenID Connect 规范的描述进行验证。

响应模式​

response_mode 决定 Casdoor 如何将授权响应或错误发送到重定向 URL:

response_modeDeliveryDefault for
queryIn the query stringresponse_type=code
fragmentIn the fragment, after #Every response type that returns a token
form_postIn a form that the browser submits to the redirect URL with POSTNone

Casdoor 绝不会将令牌放在查询字符串中。包含令牌的响应即使在使用 response_mode=query 时也会放在片段中。响应包含 state 和 iss,当包含访问令牌时还包含 token_type=Bearer。使用 form_post 时,它们是表单字段。登录页面和同意页面均支持这三种模式。

开启 Auto signin 后,仅当 response_type=code 且 response_mode 为空或 query 时,Casdoor 才会为已有会话的用户直接登录而不加载登录页面。其他请求会加载登录页面,然后由该页面完成登录。

设备授予​

将此授予用于输入受限或没有浏览器的设备,例如智能电视和 CLI 工具。

  1. 在应用的 Grant types 中开启设备授予。
  2. 向来自发现文档的 device_authorization_endpoint 发送请求。
  3. 以文本或二维码形式向用户显示响应中的 verification_uri。
  4. 用户在另一台设备上打开 URL,输入用户代码并登录。Casdoor 提供 verification_uri 背后的页面,因此您无需为其构建 UI。
  5. 同时,设备使用其 device_code 轮询令牌端点,直到用户登录为止。参见 RFC 8628, section 3.4。

您还可以在应用的 Signin methods 表中将设备登录作为登录方法提供。

让用户通过扫描二维码登录您的网站​

同样的流程允许已登录您原生应用的用户通过扫描应用生成的二维码来登录您的网站。

  1. 在 Casdoor 管理控制台中,将 Device login 添加到应用的 Signin methods,规则设置为 Login page。
  2. 在 Grant types 中开启 Device Code。

现在登录页面会在表单旁边显示一个二维码,并在二维码被批准后自动完成登录。

二维码包含 verification_uri,例如 https://<casdoor-host>/login/oauth/device/ra91hy?cancelToken=...。用户使用手机相机扫描它会在浏览器中打开 URL,然后在那里登录并批准。您的应用也可以直接使用其持有的访问令牌进行批准:

  1. 从 URL 路径中提取用户代码。在示例中,它是 ra91hy。

  2. 向用户展示他们即将登录的目标。

  3. 向 https://<casdoor-host>/api/login 发送 POST 请求,头部包含 Authorization: Bearer <access-token>,主体为:

    {
    "application": ApplicationName,
    "organization": OrganizationName,
    "type": "device",
    "userCode": "ra91hy"
    }

要拒绝登录,请将 userCode 和来自同一 URL 的 cancelToken 作为查询参数发送到 https://<casdoor-host>/api/cancel-device-auth。

多副本下的设备授予​

默认情况下,Casdoor 在内存中保存待处理的设备授权请求,这些请求将设备代码映射到用户代码。如果有多个 Casdoor 副本,设备的轮询请求和浏览器中的确认可能会到达不同的副本,从而导致流程间歇性失败。

要在副本之间共享请求,请在 conf/app.conf 中设置 redisEndpoint。Casdoor 随后会将它们存储在 Redis 中。这是用于共享会话的相同选项,格式为 host:port[,poolSize[,password[,db]]],例如 localhost:6379,100,mypassword,2,无需其他选项。第一个字段中的多个地址以 ; 分隔时使用 Redis Cluster。如果 Casdoor 在启动时无法连接到 Redis,它会记录警告并使用内存存储。请参阅配置参考。

资源所有者密码凭证授权​

仅当您的应用无法将用户重定向到 Casdoor 并且自行收集用户名和密码时,才使用此授权。

  1. 在应用的 Grant types 中启用密码授权。

  2. 向令牌端点发送一个 POST 请求:

    https://<CASDOOR_HOST>/api/login/oauth/access_token

    请求体如下:

    {
    "grant_type": "password",
    "client_id": ClientId,
    "client_secret": ClientSecret,
    "username": Username,
    "password": Password,
    }
  3. 从响应中读取令牌:

    {
    "access_token": "eyJhb...",
    "id_token": "eyJhb...",
    "refresh_token": "eyJhb...",
    "token_type": "Bearer",
    "expires_in": 10080,
    "scope": "openid"
    }

当 Casdoor 拒绝密码授权时​

仅凭密码会跳过登录页面的检查。因此,在以下情况下,Casdoor 会在令牌端点拒绝密码授权和隐式授权,并返回 invalid_grant:

Caseerror_description
The user has MFA enabledthe user has MFA enabled and cannot sign in with a password grant, please use the authorization code flow
The organization has turned off sign-inThe organization: <organization> has disabled users to signin
The user must change the password, or must set up MFA that the organization requiresthe user: <organization>/<user> must update the password or set up MFA on the login page first
The user has no local password, for example a user created through an external providerOAuth users cannot use password grant type, please use authorization code flow

应用和组织的其他登录限制(如 IP 限制)同样适用。必须更改密码或设置 MFA 的用户需先在登录页面完成这些操作,之后密码授权才能再次生效。

验证码授权​

在原生应用中,此授权用于通过电话号码或电子邮件地址以及一次性代码对用户进行身份验证,而无需打开浏览器。这是 Casdoor 的一个扩展授权类型,符合 RFC 6749 第 4.5 节的规定。如果应用允许,尚未拥有账户的地址将在同一步骤中注册。

  1. 在应用的 Grant types 中启用 Verification Code,并为应用添加 SMS 提供商、电子邮件提供商或两者。

  2. 发送验证码。向 https://<casdoor-host>/api/send-verification-code 发送包含表单数据的 POST 请求:

    FieldValue
    applicationIdadmin/<APPLICATION_NAME>
    typephone or email
    destThe phone number or email
    countryCodeThe region of a phone number, e.g. CN or US. Not needed for an E.164 number like +8613800000000
    methodlogin
    captchaTypenone, or the captcha type and captchaToken when the application's captcha provider asks for one
  3. 用验证码交换令牌。向 https://<casdoor-host>/api/login/oauth/access_token 发送 POST 请求:

    {
    "grant_type": "urn:casdoor:params:oauth:grant-type:verification-code",
    "client_id": ClientId,
    "username": "+8613800000000",
    "code": "123456",
    "scope": "openid profile"
    }

    username 是接收验证码的电话号码或电子邮件地址。对于采用国家格式的电话号码,还需发送 country_code。

该授权不需要客户端密钥,因此适用于公共客户端。响应与其他授权相同,包含一个用于保持用户登录状态的 refresh_token。

错误的验证码会计入应用的 Failed signin limit。Casdoor 拒绝启用了 MFA 的用户。对于这类用户,请使用授权码授权。

使用验证码注册新用户​

如果没有用户拥有该电话号码或电子邮件地址,且满足以下所有条件,则授权将创建用户,就像注册页面一样:

  • 应用的 Enable signup 已开启,且 Disable self signup 已关闭。
  • 应用的 Signup items 不要求超出验证码所能证明的内容。只有 ID、Username、Display name、Password、Confirm password、Agreement、Signup button 和 Providers 可以是必填项,此外,当用户使用电子邮件注册时,Email 也可以是必填项;当用户使用电话号码注册时,Phone 也可以是必填项。默认注册项目要求同时提供 Email 和 Phone,因此请将另一个设为可选。
  • 对于电话号码,其地区必须在组织的 Supported country codes 中。

否则,/api/send-verification-code 将回答用户不存在,只有现有用户可以登录。

移动一键授权​

在中国大陆的原生应用也可以通过设备上的电话号码对用户进行身份验证,而无需短信代码:阿里云 PNVS 的一键登录 SDK 返回一个令牌,应用使用该令牌与授权类型 urn:casdoor:params:oauth:grant-type:mobile-one-click 进行交换。请参阅移动一键登录。

客户端凭证授权​

将此授权用于机器对机器的调用,此时没有用户参与。

  1. 在应用的 Grant types 中启用客户端凭证授权。

  2. 向 https://<casdoor-host>/api/login/oauth/access_token 发送 POST 请求:

    {
    "grant_type": "client_credentials",
    "client_id": ClientId,
    "client_secret": ClientSecret,
    }
  3. 从响应中读取令牌:

    {
    "access_token": "eyJhb...",
    "id_token": "eyJhb...",
    "refresh_token": "eyJhb...",
    "token_type": "Bearer",
    "expires_in": 10080,
    "scope": "openid"
    }

与上述授权的令牌不同,此访问令牌属于应用而非用户。

刷新令牌授权​

使用先前响应中的刷新令牌获取新的访问令牌。

  1. 在应用的 Refresh token expire 中设置刷新令牌的有效期。默认为 0 小时。

  2. 向 https://<casdoor-host>/api/login/oauth/refresh_token 发送 POST 请求:

    {
    "grant_type": "refresh_token",
    "refresh_token": REFRESH_TOKEN,
    "scope": SCOPE,
    "client_id": ClientId,
    "client_secret": ClientSecret,
    }
  3. 从响应中读取令牌:

    {
    "access_token": "eyJhb...",
    "id_token": "eyJhb...",
    "refresh_token": "eyJhb...",
    "token_type": "Bearer",
    "expires_in": 10080,
    "scope": "openid"
    }

Casdoor 按以下方式检查刷新请求:

  • 如果令牌是由发送了 client_secret 的授权码交换或由令牌交换签发的,则刷新请求必须包含正确的 client_secret。否则,Casdoor 返回 invalid_client。使用 PKCE 且无密钥的公共客户端在没有密钥的情况下刷新。
  • 刷新令牌必须属于请求的应用。否则,Casdoor 返回 invalid_grant 以及 the token is for wrong application (client_id)。
  • 请求中的 scope 必须是原始 scope 的子集。如果省略该参数,新令牌将具有原始 scope。
  • 未知或已撤销的刷新令牌会导致失败,错误为 invalid_grant 和 refresh token is invalid or revoked。已被 Casdoor 无效化的刷新令牌(例如在注销时)会导致失败,错误为 invalid_grant 和 refresh token is expired。

重命名用户不会使该用户的刷新令牌失效。有关确实会撤销令牌的事件,请参阅 Casdoor 何时撤销令牌。

刷新令牌轮换​

默认情况下,每次刷新都会返回一个新的刷新令牌并撤销之前使用的那个,正如 RFC 9700 对公共客户端所建议的那样。请在每次刷新后存储新的刷新令牌。已经使用过的刷新令牌会导致失败,错误为 invalid_grant。

轮换会破坏那些多个进程共享一个刷新令牌的客户端,例如从环境变量中使用令牌运行并行任务的 CLI:第一次刷新会为所有其他进程撤销该令牌。对于此类客户端,请在应用的 OIDC/OAuth 设置中开启 Disable refresh token rotation。然后:

  • 刷新操作返回相同的刷新令牌,该令牌保持其原始过期时间。
  • 早期刷新生成的访问令牌仍然有效,直到它们过期。
  • 注销操作仍会为所有进程撤销该刷新令牌。
注意事项

如果不进行轮换,泄露的刷新令牌在过期前一直有效。请将 Refresh token expire 设置为较短的时间,并为公共客户端优先使用 DPoP。

令牌交换授权​

令牌交换 (RFC 8693) 将一个令牌交换为具有不同属性的新令牌。当某个服务代表用户调用另一个服务时使用此功能,或者在将令牌传递给下游服务之前缩小其范围。例如,API 网关在将请求转发给微服务之前,会将具有广泛范围的令牌交换为具有狭窄范围的令牌,以便每个服务仅获得其所需的权限。

向 https://<casdoor-host>/api/login/oauth/access_token 发送 POST 请求:

{
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"client_id": ClientId,
"client_secret": ClientSecret,
"subject_token": SubjectToken,
"subject_token_type": "urn:ietf:params:oauth:token-type:access_token",
"scope": "openid email"
}
Parameter描述
subject_tokenThe token to exchange, typically an access token or a JSON Web Token (JWT) that you already hold
subject_token_typeurn:ietf:params:oauth:token-type:access_token (default), urn:ietf:params:oauth:token-type:jwt, or urn:ietf:params:oauth:token-type:id_token
scopeOptional. A subset of the scope of the subject token. If you omit it, the new token has the scope of the subject token
audienceOptional. The application that the new access token is for, by its client ID or by its application name. The aud claim of the new access token is then the client ID of that application, and the aud of the new ID token stays the requesting client

响应中包含一个与主体令牌属于同一用户的新令牌:

{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid email"
}

Casdoor 使用颁发该令牌的应用的证书来验证主体令牌,该应用由 azp 声明标识,而不是使用请求客户端的证书。如果请求客户端不是颁发者,则主体令牌的 aud 声明必须包含请求客户端的客户端 ID。否则,Casdoor 将以 invalid_grant 拒绝交换。这防止了一个应用在未被指定为受众的情况下交换另一个应用的令牌(RFC 8693,第 2.1 节)。此规则适用于每种 Token format,包括 JWT-Standard。

Casdoor 在以下情况下也会拒绝交换:

CaseError
主体令牌不是 Casdoor 的活动令牌,例如因为它已被撤销或已过期。当 subject_token_type 设置为 urn:ietf:params:oauth:token-type:id_token 时,Casdoor 将该令牌视为 ID 令牌进行查找,否则视为访问令牌invalid_grant, subject_token is revoked or unknown
The subject token has no user, for example a token of the client credentials grantinvalid_grant, subject_token has no user
The user is forbidden to sign ininvalid_grant
The user isn't in the organization of the requesting application, and the application isn't sharedinvalid_grant
audience isn't a known applicationinvalid_target
The audience application isn't in the organization of the user, and isn't sharedinvalid_target

外部颁发者的令牌也可以作为主体令牌,无需客户端密钥。请参阅 联合凭证。

JWT 承载授权​

通过 JWT 承载授权 (RFC 7523),客户端通过提供签名的 JWT 断言而不是客户端密钥来获取访问令牌。它用于客户端持有私钥且您不希望共享长期存在的秘密的服务间调用。

  1. 在应用的 Grant types 中开启 JWT Bearer。

  2. 在应用的 Security 选项卡的 Client cert 中上传客户端证书。Casdoor 使用该证书的公钥来验证断言。

  3. 创建断言:一个使用客户端私钥签名并包含以下声明的 JWT:

    ClaimDescription
    iss签发者:应用的 client_id
    sub主体:应用的 client_id
    aud受众 — Casdoor 令牌端点 URL
    exp过期时间(Unix 时间戳)
  4. 向 https://<casdoor-host>/api/login/oauth/access_token 发送 POST 请求:

    {
    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": "<signed-JWT>",
    "client_id": "CLIENT_ID"
    }
  5. 从响应中读取令牌:

    {
    "access_token": "eyJhb...",
    "token_type": "Bearer",
    "expires_in": 10080,
    "scope": "openid"
    }

Casdoor 验证签名和标准 JWT 声明。访问令牌属于该应用,这与客户端凭证授权一样。

JWT 承载授权的 assertion 也可以是应用信任的外部颁发者的令牌。请参阅 联合凭证。

联合凭证(工作负载身份)​

通过联合凭证,应用信任外部 OpenID Connect 颁发者(如 GitHub Actions、Kubernetes、云工作负载身份或其他 IdP)的令牌作为其凭证。已经持有此类令牌的工作负载无需客户端密钥或客户端证书即可获得 Casdoor 令牌。

  1. 在 Casdoor 管理控制台中,打开应用并转到 OIDC/OAuth 选项卡。

  2. 在 Federated credentials 中,为您信任的每个颁发者和主体添加一行:

    ColumnDescription
    IssuerThe issuer of the external tokens. It must equal the iss claim exactly, for example https://token.actions.githubusercontent.com
    JWKS URLThe URL of the signing keys of the issuer. If you leave it empty, Casdoor reads jwks_uri from <issuer>/.well-known/openid-configuration, whose issuer must match
    SubjectRequired. The sub claim to accept. * matches any text, for example repo:my-org/my-repo:*
    Audience要接受的 aud 值。如果留空,Casdoor 接受其自身的源、其令牌端点 https://<casdoor-host>/api/login/oauth/access_token 或应用的客户端 ID
    UserThe user that the token stands for: a username, or {claim} to take the username from a claim, for example {email}. If you leave it empty, the token stands for the application itself
    Enable signup当映射的用户尚不存在时,在其首次使用此发行者的令牌登录时创建该用户。仅在设置了 User 时可用
  3. 在 Grant types 中,开启工作负载使用的授权类型。

  4. 单击保存。

然后,工作负载以三种方式之一呈现其外部令牌:

  • 在令牌端点作为 client_assertion,配合 client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer,在任何授权中对客户端进行身份验证。同时在请求中发送 client_id,因为外部令牌的 sub 不是客户端 ID。
  • 作为 JWT 承载授权 的 assertion。
  • 作为 令牌交换授权 的 subject_token。无需客户端密钥。

例如,GitHub Actions 作业将其 OIDC 令牌交换为 Casdoor 令牌:

curl -X POST https://<casdoor-host>/api/login/oauth/access_token \
-d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
-d client_id=<client-id> \
-d subject_token=<github-oidc-token> \
-d subject_token_type=urn:ietf:params:oauth:token-type:jwt

Casdoor 按如下方式验证外部令牌:

  • 签名使用颁发者的密钥进行验证。Casdoor 会将密钥缓存一小时,并且当令牌具有未知的 kid 时,每分钟最多重新获取一次。
  • 签名算法为 RS256、RS384、RS512、PS256、PS384、PS512、ES256、ES384、ES512 或 EdDSA 之一。
  • 令牌必须包含 exp 声明。Casdoor 允许一分钟的时钟偏差。
  • 如果受信任颁发者的令牌的主体(subject)与任何记录都不匹配,则验证失败,例如错误信息为:the subject: <sub> of issuer: <issuer> is not trusted by application: [<application>]。

With User empty, the new token is an application token, as with the client credentials grant, without a refresh token or an ID token. Otherwise, it's a token of the mapped user in the organization of the application. If the token lacks the claim, Casdoor returns invalid_grant. If the user doesn't exist, Casdoor returns invalid_grant too, unless Enable signup is on for the row.

发现文档在 token_endpoint_auth_methods_supported 中列出了 private_key_jwt。

无需 Casdoor 页面即可注册和登录用户​

启用 Enable signup 后,已经验证用户身份的服务可以在不显示任何 Casdoor 页面的情况下,为用户分配一个 Casdoor 账户和一个 Casdoor 令牌。例如,移动应用通过其自身的登录服务,使用学生的学校账户来登录学生。该登录服务是一个带有 JWKS 的 OIDC 发行者,在成功登录后,它会签发一个短期有效的 JWT,如下所示:

{
"iss": "https://login.example.edu",
"sub": "student:2021001",
"aud": "casdoor",
"exp": 1765432100,
"student_id": "2021001",
"name": "Alice",
"email": "alice@example.edu",
"email_verified": true
}

为了接受该令牌,请添加一行配置,其中 Issuer 为 https://login.example.edu,Subject 为 student:*,Audience 为 casdoor,User 为 {student_id},并开启 Enable signup,同时在 Grant types 中启用 JWT Bearer。随后,应用或登录服务将使用该 JWT 换取一个 Casdoor 令牌:

curl -X POST https://<casdoor-host>/api/login/oauth/access_token \
-d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
-d client_id=<client-id> \
-d assertion=<jwt> \
-d scope=openid

响应包含用户的访问令牌、刷新令牌和 ID 令牌。在学生首次交换令牌时,Casdoor 按以下方式创建用户:

  • 用户名是映射声明的值。它必须是有效的用户名或电子邮件地址,否则 Casdoor 返回 invalid_grant 并且不创建任何内容。
  • 显示名称来自 name,电子邮件来自 email 和 email_verified,头像来自 picture(如果令牌中包含这些字段)。
  • 用户加入应用的 Default group 并获得其 Default tag。如果启用了注册审批,用户将等待审批,在此之前无法获取令牌。
  • 后续使用相同声明值的交换操作将登录同一用户。并发执行的首次交换操作只会创建一个用户。

即使应用本身不允许注册,此功能也能正常工作,因为只有受信任的发行者才能以此方式创建用户。此功能不适用于共享应用。

DPoP(绑定发送方的令牌)​

Casdoor 支持 持有者证明 (DPoP, RFC 9449)。DPoP 将访问令牌绑定到客户端持有的密钥,因此即使令牌泄露,如果没有私钥也无法使用。

要获取 DPoP 绑定的令牌,请在令牌请求中发送包含 DPoP 证明 JWT 的 DPoP 标头:

POST /api/login/oauth/access_token
DPoP: <DPoP proof JWT>

Casdoor 通过其 JWK 指纹 (jkt) 将令牌绑定到证明的公钥,并返回 token_type 为 DPoP 而不是 Bearer:

{
"access_token": "eyJhb...",
"token_type": "DPoP",
"expires_in": 10080,
"scope": "openid"
}

刷新令牌请求接受相同的 DPoP 标头。Casdoor 会以错误 invalid_dpop_proof 拒绝无效证明。如果使用 DPoP 签发的刷新令牌,它也绑定到该密钥:刷新它需要使用相同密钥签名的 DPoP 证明。如果没有证明,或者使用了其他密钥的证明,刷新将失败并返回 invalid_dpop_proof。Casdoor 会针对令牌端点 https://<casdoor-host>/api/login/oauth/access_token 检查刷新证明的 htu 声明。

发现文档在 dpop_signing_alg_values_supported 中列出了 Casdoor 接受的用于证明的签名算法:

{
"dpop_signing_alg_values_supported": ["RS256", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512"]
}

令牌内省响应在 cnf.jkt 声明中显示密钥绑定(RFC 9449,第 8 节)。

验证访问令牌​

Casdoor 支持 令牌内省 (RFC 7662)。使用 HTTP Basic 认证对请求进行身份验证,用户名为客户端 ID,密码为客户端密钥:

POST /api/login/oauth/introspect HTTP/1.1
Host: CASDOOR_HOST
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=

token=ACCESS_TOKEN&token_type_hint=access_token

示例响应:

{
"active": true,
"client_id": "c58c...",
"username": "admin",
"token_type": "Bearer",
"exp": 1647138242,
"iat": 1646533442,
"nbf": 1646533442,
"sub": "7a6b4a8a-b731-48da-bc44-36ae27338817",
"aud": [
"c58c..."
],
"iss": "http://localhost:8000"
}

或者,您可以使用应用证书的公钥或 JWKS 端点的密钥自行验证令牌签名。SDK 会在 ParseJwtToken() 中执行此操作。

撤销令牌​

Casdoor 支持 令牌撤销 (RFC 7009)。发送包含表单参数的 POST 请求:

POST /api/login/oauth/revoke HTTP/1.1
Host: CASDOOR_HOST
Content-Type: application/x-www-form-urlencoded
Authorization: Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=

token=REFRESH_TOKEN&token_type_hint=refresh_token
ParameterRequiredDescription
tokenYes要撤销的访问令牌或刷新令牌
token_type_hintNoaccess_token 或 refresh_token。Casdoor 首先将此类型作为查找依据,然后再尝试另一种类型
client_idYes应用的客户端 ID。通过 HTTP Basic 认证或作为表单参数发送
client_secretSee description应用的客户端密钥。对于不使用 PKCE 的授权码模式、客户端凭证模式和令牌交换模式颁发的令牌,此项为必填。使用了 PKCE 的公共客户端只需发送 client_id

同一授权下的访问令牌和刷新令牌会被一起撤销。如果刷新令牌被多个访问令牌共享(因为未启用 refresh token rotation),则所有这些令牌都会被撤销。当令牌被撤销、已过期、未知或属于另一个应用时,Casdoor 返回 HTTP 200 且响应体为空。缺少 client_id、未知的客户端或错误的客户端密钥将返回 HTTP 401 及 invalid_client,缺少 token 将返回 HTTP 400 及 invalid_request。

使用访问令牌​

发送访问令牌以调用 Casdoor API。例如,通过以下两种方式之一使用 GET 或 POST 调用 /api/userinfo:

  • 使用 Authorization 标头:Authorization: Bearer <access-token>
  • 使用查询参数:https://<casdoor-host>/api/userinfo?accessToken=<access-token>

Casdoor 返回令牌范围允许的字段的用户信息:

{
"sub": "7a6b4a8a-b731-48da-bc44-36ae27338817",
"iss": "http://localhost:8000",
"aud": "c58c..."
}

要获取更多字段,请在授权请求中请求更多范围。

UserInfo 和 get-account​

EndpointReturns
/api/userinfoThe standard OpenID Connect (OIDC) claims of the user, limited by the scopes of the token
/api/get-account已登录账户的完整用户对象。此端点是 Casdoor 特有的。如果存在外部 OAuth 提供商,则包括其访问令牌

获取外部提供商的访问令牌​

当用户通过 GitHub 或 Google 等外部 OAuth 提供商登录时,Casdoor 会将该提供商的访问令牌存储在用户的 originalToken 字段中。您的应用程序可以使用它在代表用户调用提供商 API(如 GitHub API 或 Google Drive API)时,无需再次进行 OAuth 流程。

从 /api/get-account 读取令牌:

{
"status": "ok",
"data": {
"name": "user123",
"originalToken": "ya29.a0AfH6SMBx...",
...
}
}

Casdoor 仅向用户和管理员返回 originalToken。对于所有其他请求者,它会掩码该字段。

另请参阅​