OAuth 2.0
Casdoor is an OAuth 2.0 authorization server. This page describes how to get an access token with each grant type, how to verify a token, and how to use it. If you prefer not to call the endpoints yourself, use a Casdoor SDK or a standard OIDC client.
Endpoints
| Endpoint | URL |
|---|---|
| Authorization | https://<casdoor-host>/login/oauth/authorize |
| Token | https://<casdoor-host>/api/login/oauth/access_token |
| Refresh token | https://<casdoor-host>/api/login/oauth/refresh_token |
| Token introspection | https://<casdoor-host>/api/login/oauth/introspect |
| Token revocation | https://<casdoor-host>/api/login/oauth/revoke |
| Pushed authorization request | https://<casdoor-host>/api/login/oauth/par |
| Backchannel authentication | https://<casdoor-host>/api/login/oauth/bc-authorize |
| UserInfo | https://<casdoor-host>/api/userinfo |
In the examples, ClientId and ClientSecret are the Client ID and the Client secret of the Casdoor application.
Supported grant types
| Grant Type | RFC | Use Case |
|---|---|---|
| Authorization Code | RFC 6749 §4.1 | Default; web/mobile apps with a backend. Enabled by default. |
| Implicit | RFC 6749 §4.2 | Frontend-only apps without a backend. |
| Resource Owner Password | RFC 6749 §4.3 | Apps with no frontend redirect; user credentials sent directly. |
| Client Credentials | RFC 6749 §4.4 | Service-to-service calls with no user involved. |
| Refresh Token | RFC 6749 §6 | Renew an access token without re-authenticating. |
| Device Authorization | RFC 8628 | Devices with limited input or no browser. |
| Token Exchange | RFC 8693 | Swap an existing token for one with different scope or audience. |
| JWT Bearer | RFC 7523 | Service auth using a signed JWT assertion instead of a client secret. |
| CIBA | OpenID Connect CIBA Core 1.0 | Sign-ins started by someone else, e.g. a call center or a bank counter, that the user approves on their own device. |
| Verification Code | Casdoor extension | Native apps that sign users in (and up) with a code sent by SMS or email. |
| Mobile One-Click | Casdoor extension | Native apps that sign users in (and up) with the phone number of the device, through Alibaba Cloud PNVS. |
The authorization code grant is on by default. Turn on the other grant types in Grant types on the edit page of the application.

Authorization code grant
Use this grant for applications that sign users in through the browser. It is the recommended grant.
-
Redirect the user to the authorization endpoint:
https://<CASDOOR_HOST>/login/oauth/authorize?
client_id=CLIENT_ID&
redirect_uri=REDIRECT_URI&
response_type=code&
scope=openid&
state=STATE -
The user signs in. Casdoor redirects the browser to your redirect URL with an authorization code:
https://REDIRECT_URI?code=CODE&state=STATE&iss=ISSUERissis the issuer URL of Casdoor, as defined by RFC 9207. Compare it with theissuerof the discovery document to make sure that the response comes from the Casdoor server that you sent the user to. Casdoor addsissto every authorization response and to every error that it sends back to the redirect URL, and the discovery document announces this with"authorization_response_iss_parameter_supported": true. -
Exchange the code for tokens. Send a
POSTrequest to the token endpoint:https://<CASDOOR_HOST>/api/login/oauth/access_tokenWith the body:
{
"grant_type": "authorization_code",
"client_id": ClientId,
"client_secret": ClientSecret,
"code": Code,
} -
Read the tokens from the response:
{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
An authorization code is valid for 5 minutes and works once. A second exchange of the same code fails with invalid_grant and the description authorization code has been used for token: [...].
The responses of the token endpoint and the refresh token endpoint carry the headers Cache-Control: no-store and Pragma: no-cache, so that no cache keeps the tokens.
Scopes
Request scopes with the scope parameter of the authorization URL. They determine which user fields the tokens and the UserInfo endpoint return.
| Scope | Description |
|---|---|
| openid (default) | sub, iss, aud |
| profile | name, displayName, avatar |
| email address | |
| address | address (OIDC object in JWT-Standard; see OIDC address claim) |
| phone | phone number |
Separate several scopes with %20:
https://<CASDOOR_HOST>/login/oauth/authorize?
client_id=...&
scope=openid%20email
For the claims behind each scope, see the OpenID Connect specification.
PKCE
Casdoor supports Proof Key for Code Exchange (PKCE), which protects the authorization code of public clients such as mobile and single-page applications.
-
Generate a random code verifier of 43 to 128 characters.
-
Compute the code challenge: the Base64-URL-encoded SHA-256 hash of the verifier.
-
Add two parameters to the authorization URL:
&code_challenge_method=S256&code_challenge=YOUR_CHALLENGE -
Add the
code_verifierparameter, with the original verifier, to the token request.
With PKCE, client_secret is optional in the token request. If you send it, it must be correct.
When Casdoor itself signs users in at an external OAuth provider that requires PKCE, such as Twitter or a custom provider with PKCE turned on, Casdoor generates the code verifier for each flow. You don't implement PKCE for that part.
Pushed authorization requests (PAR)
With PAR (RFC 9126), your backend sends the parameters of the authorization request to Casdoor first, and the browser only carries a short reference to them. The user can't see or change redirect_uri, scope, state, or the PKCE challenge on the way. FAPI 2.0 requires it.
-
Send the parameters that would go into the authorization URL to the PAR endpoint, with the client credentials:
curl -u ClientId:ClientSecret https://<casdoor-host>/api/login/oauth/par -d response_type=code -d redirect_uri=https://app.example.com/callback -d scope=openid -d state=STATE -d code_challenge=YOUR_CHALLENGE -d code_challenge_method=S256Casdoor checks them as it checks an authorization request and answers with status
201:{
"request_uri": "urn:ietf:params:oauth:request_uri:1adab98a7ac1c2af6ef06d5ad5541328d6b821c2",
"expires_in": 90
} -
Within 90 seconds, send the user to the authorization endpoint with only the client ID and the
request_uri:https://<casdoor-host>/login/oauth/authorize?client_id=ClientId&request_uri=urn:ietf:params:oauth:request_uri:1adab98a7ac1c2af6ef06d5ad5541328d6b821c2 -
The rest is the same as the authorization code grant: Casdoor redirects back with a code, and you exchange it at the token endpoint.
A request_uri works once. The client authenticates at the PAR endpoint with client_secret_basic, client_secret_post, or a client assertion. A public client without a secret can push too, but only with a PKCE challenge. You can also push a request object in the request parameter.
To refuse every authorization request of an application that didn't come through PAR, turn on Require PAR in the OIDC/OAuth tab of the application. The application's discovery document then reports require_pushed_authorization_requests: true. Turn it on only when the application uses PAR, or its users can't sign in.
Bind a token to one service
If your application calls several backend services, you can bind a token to one of them, so that a token that was issued for one service can't be used at another. Casdoor supports Resource Indicators (RFC 8707) for this.
-
Add the
resourceparameter, with an absolute URI that identifies the service, to the authorization URL: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 -
Send the same
resourcein the token request:{
"grant_type": "authorization_code",
"client_id": ClientId,
"client_secret": ClientSecret,
"code": Code,
"resource": "https://api.example.com"
}
The aud (audience) claim of the access token is then the resource URI and not the client ID. The service verifies that a token was issued for it by checking aud. The value of resource must be exactly the same in both requests.
Casdoor carries the resource parameter through interactive sign-in. If the user has to enter a password, complete multi-factor authentication (MFA), use WebAuthn, or approve the consent page, the parameter survives the redirects. It's also kept when Casdoor signs the user in automatically with an existing session.
When you refresh the token, the new access token keeps the aud of the original grant. You can repeat resource in the refresh request, as a query parameter or a field of the body. If you do, it must be the same value as in the original grant. Otherwise, Casdoor returns invalid_grant with the description resource parameter does not match the original grant.
Skip the sign-in page with a provider hint
To send the user straight to one OAuth provider, without showing the Casdoor sign-in page, add provider_hint=<provider-name> to the authorization URL:
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 then serves a small redirect page, without loading the full frontend, and sends the user to the provider. This shortens the time to the redirect on slow devices and connections.
Sign-up in the authorization flow
A user who creates an account during the authorization flow is redirected to your redirect URL with an authorization code as soon as the sign-up completes, exactly as after a sign-in. Casdoor carries the authorization parameters, such as client_id, response_type, and redirect_uri, through the sign-up. Your application needs no changes for this.
Control the sign-in prompt
By default, a user who already has a Casdoor session can be signed in without entering credentials again. Add the OpenID Connect parameters prompt and max_age to the authorization URL to change this:
| Parameter | Effect |
|---|---|
prompt=login | The user must enter credentials again, even with an existing session |
max_age=<seconds> | The user must enter credentials again if they last entered them more than <seconds> seconds ago, or if Casdoor doesn't know when they did |
prompt=none | Casdoor shows no page. It signs the user in with the existing session, or sends an error back to the redirect URL |
prompt takes a space-separated list of values. When the existing session doesn't satisfy prompt=login or max_age, a sign-in with that session fails with login_required and the message Please sign in again. The time at which the user entered credentials is in the auth_time claim of the ID token.
Use prompt=none to check, for example from a hidden iframe, whether the user is still signed in. Casdoor then skips the automatic redirect to a single provider, and answers in the same way as a successful response would go, with state and iss, and with one of these errors:
| Error | Reason |
|---|---|
login_required | No Casdoor session, the user of the session isn't in the organization of the application, or the session doesn't satisfy max_age |
consent_required | The user must approve the consent page first |
interaction_required | The user must update the password, set up or complete MFA, select a plan, or fill in the prompt page first |
access_denied | The sign-in failed for another reason. error_description says why |
server_error | The request to Casdoor failed |
Suggest the account with login_hint
Add login_hint=<username or email> to the authorization URL when your application already knows who signs in. Casdoor fills in the username on its sign-in page, and passes the hint on to the identity provider that the user picks:
| Provider | Casdoor adds to the URL of the provider |
|---|---|
| Google, Azure AD, Azure AD B2C, Microsoft Online, Okta, Auth0, ADFS, Casdoor, and custom OAuth and OIDC providers | login_hint |
| GitHub | login |
| SAML providers with the redirect binding, such as Microsoft Entra ID | login_hint on the SSO URL |
The provider then preselects or fills in the account. SAML providers that use the POST binding, which Casdoor uses when Sign request is on, don't get the hint.
Implicit grant
Use this grant only for applications without a backend. Prefer the authorization code grant with PKCE.
-
In Grant types of the application, turn on Token to return an access token, ID Token to return an ID token, or both.
-
Redirect the user to:
https://<CASDOOR_HOST>/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=token&scope=openid&state=STATE -
After the user signs in, Casdoor redirects the browser to:
https://REDIRECT_URI#access_token=ACCESS_TOKEN&token_type=Bearer&state=STATE&iss=ISSUER
response_type can be token, id_token, or id_token token. The authorization endpoint never returns a refresh token. If the grant type that a response type needs isn't turned on, Casdoor shows Grant_type: token is not supported in this application (or id_token).
When scope contains openid and the response contains an ID token, send a nonce parameter. Casdoor copies it into the ID token, and refuses the request without it: The nonce parameter is required for this response type.
The implicit grant at the token endpoint (grant_type=token with a username and a password) requires a user with a local password. Users who were created only through an external provider and have no local password can't use it and receive invalid_grant. The same rules as for the password grant apply. Use the authorization code grant for these users.
Hybrid flow
In the OpenID Connect hybrid flow, the authorization endpoint returns an authorization code together with tokens. Your frontend can use the tokens at once, and your backend exchanges the code as in the authorization code grant.
response_type is a space-separated combination of code, token, and id_token. The hybrid values are:
response_type | The authorization endpoint returns |
|---|---|
code id_token | code and id_token |
code token | code and access_token |
code token id_token | code, access_token, and id_token |
-
In Grant types of the application, turn on Token for a response type that contains
token, and ID Token for one that containsid_token. -
Redirect the user to the authorization endpoint with the response type and a
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=NONCEnonceis required whenscopecontainsopenidand the response type containsid_token, or iscode token. -
After the user signs in, Casdoor redirects the browser to your redirect URL. The values are in the fragment, unless you ask for another response mode.
-
Exchange the code at the token endpoint. Only this exchange returns a refresh token.
The ID token carries these claims of the OpenID Connect specification:
| Claim | When it's present |
|---|---|
auth_time | When Casdoor knows the time at which the user last entered credentials |
at_hash | When the ID token comes with an access token, and in the ID token of the authorization code grant |
c_hash | When the ID token comes with an authorization code |
at_hash and c_hash use SHA-256, or SHA-384 or SHA-512 when the Token signing method of the application ends in 384 or 512. Verify them as the OpenID Connect specification describes.
Response modes
response_mode decides how Casdoor sends the authorization response, or the error, to the redirect URL:
response_mode | Delivery | Default for |
|---|---|---|
query | In the query string | response_type=code |
fragment | In the fragment, after # | Every response type that returns a token |
form_post | In a form that the browser submits to the redirect URL with POST | None |
Casdoor never puts tokens in the query string. A response that contains a token goes in the fragment, even with response_mode=query. The response contains state and iss, and token_type=Bearer when it contains an access token. With form_post, they are fields of the form. The sign-in page and the consent page both support all three modes.
With Auto signin on, Casdoor signs a user who has a session in without loading the sign-in page only for response_type=code with response_mode empty or query. Other requests load the sign-in page, which then completes the sign-in.
Device grant
Use this grant for devices with limited input or without a browser, such as smart TVs and CLI tools.
- Turn on the device grant in Grant types of the application.
- Send a request to the
device_authorization_endpointfrom the discovery document. - Show the
verification_urifrom the response to the user, as text or as a QR code. - The user opens the URL on another device, enters the user code, and signs in. Casdoor provides the page behind
verification_uri, so you don't build a UI for it. - Meanwhile, the device polls the token endpoint with its
device_codeuntil the user has signed in. See RFC 8628, section 3.4.
You can also offer device login as a sign-in method in the Signin methods table of the application.
Let users sign in to your website by scanning a QR code
The same flow lets users who are signed in to your native app sign in to your website by scanning a QR code with the app.
- In the Casdoor admin console, add Device login to the Signin methods of the application, with the rule Login page.
- Turn on Device Code in Grant types.
The sign-in page now shows a QR code next to the form and completes the sign-in on its own once the QR code is approved.
The QR code contains the verification_uri, for example https://<casdoor-host>/login/oauth/device/ra91hy?cancelToken=.... A user who scans it with the camera of a phone opens the URL in the browser, signs in, and approves there. Your app can approve it directly instead, with the access token that it already holds:
-
Take the user code from the path of the URL. In the example, it is
ra91hy. -
Show the user what they are about to sign in to.
-
Send a
POSTrequest tohttps://<casdoor-host>/api/loginwith the headerAuthorization: Bearer <access-token>and the body:{
"application": ApplicationName,
"organization": OrganizationName,
"type": "device",
"userCode": "ra91hy"
}
To reject the sign-in, send userCode and the cancelToken from the same URL as query parameters to https://<casdoor-host>/api/cancel-device-auth.
Device grant with several replicas
By default, Casdoor keeps pending device authorization requests, which map device codes to user codes, in memory. With several replicas of Casdoor, the polling request of the device and the confirmation in the browser can reach different replicas, and the flow then fails intermittently.
To share the requests between replicas, set redisEndpoint in conf/app.conf. Casdoor then stores them in Redis. This is the same option that shares sessions, in the format host:port[,poolSize[,password[,db]]], for example localhost:6379,100,mypassword,2, and no further option is needed. Several addresses in the first field, separated by ;, use Redis Cluster. If Casdoor can't reach Redis at startup, it logs a warning and uses the in-memory store. See the Configuration reference.
CIBA
With OpenID Connect Client-Initiated Backchannel Authentication (CIBA), the sign-in starts somewhere other than the user's browser: an agent in a call center, a bank counter, a point-of-sale terminal, or an AI agent that needs the user's approval. The application names the user, Casdoor asks the user to approve on their own device, and the application gets the tokens without a redirect. Casdoor supports the poll mode.
-
Turn on CIBA in Grant types of the application, and add an Email provider to its Providers. Casdoor emails the user the link to approve.
-
Send the request to the backchannel authentication endpoint, with the client credentials:
curl -u ClientId:ClientSecret https://<casdoor-host>/api/login/oauth/bc-authorize -d scope=openid -d login_hint=alice@example.com -d binding_message="Transfer 8842"Parameter Description scopeRequired, must contain openid.login_hintThe username, email, or phone number of the user in the application's organization. id_token_hintAn ID token that Casdoor issued to the application for the user. Send this or login_hint, not both.binding_messageOptional, at most 100 characters. Show the same text on your side, so that the user can tell the request is yours. requested_expiryOptional, seconds the request stays valid. The default is 300, the maximum 1800. The response:
{
"auth_req_id": "7304fbfe7925a1578199ffd54a2b2ecf917004f84f7cc49009634fee3e4d2982",
"expires_in": 300,
"interval": 5
} -
Casdoor emails the user a link to
https://<casdoor-host>/ciba/<organization>/<id>. The user signs in there, sees the application, the binding message, and the scope, and approves or denies. -
Meanwhile, poll the token endpoint every
intervalseconds:curl -u ClientId:ClientSecret https://<casdoor-host>/api/login/oauth/access_token -d grant_type=urn:openid:params:grant-type:ciba -d auth_req_id=AUTH_REQ_IDUntil the user answers, the response is the error
authorization_pending. Polling faster thanintervalreturnsslow_downand adds 5 seconds to the interval. After the user approves, the response contains the access token, ID token, and refresh token. A denied request returnsaccess_denied, an expired oneexpired_token.
The backchannel authentication endpoint returns unknown_user_id when no user matches the hint, and access_denied when the user has no email address. Casdoor keeps pending CIBA requests in memory: with several replicas, route the requests of one client to the same replica.
Resource owner password credentials grant
Use this grant only when your application can't redirect the user to Casdoor and collects the username and password itself.
-
Turn on the password grant in Grant types of the application.
-
Send a
POSTrequest to the token endpoint:https://<CASDOOR_HOST>/api/login/oauth/access_tokenWith the body:
{
"grant_type": "password",
"client_id": ClientId,
"client_secret": ClientSecret,
"username": Username,
"password": Password,
} -
Read the tokens from the response:
{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
When Casdoor refuses the password grant
A password alone would skip the checks of the sign-in page. Casdoor therefore refuses the password grant, and the implicit grant at the token endpoint, with invalid_grant in these cases:
| Case | error_description |
|---|---|
| The user has MFA enabled | the user has MFA enabled and cannot sign in with a password grant, please use the authorization code flow |
| The organization has turned off sign-in | The organization: <organization> has disabled users to signin |
| The user must change the password, or must set up MFA that the organization requires | the 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 provider | OAuth users cannot use password grant type, please use authorization code flow |
The other sign-in restrictions of the application and the organization, such as IP restrictions, apply as well. A user who must change the password or set up MFA does that on the sign-in page first, after which the password grant works again.
Verification code grant
Use this grant in native apps that sign users in with a phone number or an email address and a one-time code, without opening a browser. It is an extension grant of Casdoor, as allowed by RFC 6749, section 4.5. If the application allows it, an address that has no account yet is signed up in the same step.
-
Turn on Verification Code in Grant types of the application, and add an SMS provider, an email provider, or both to the application.
-
Send the code. Send a
POSTrequest with form data tohttps://<casdoor-host>/api/send-verification-code:Field Value applicationIdadmin/<APPLICATION_NAME>typephoneoremaildestThe phone number or email countryCodeThe region of a phone number, e.g. CNorUS. Not needed for an E.164 number like+8613800000000methodlogincaptchaTypenone, or the captcha type andcaptchaTokenwhen the application's captcha provider asks for one -
Exchange the code for tokens. Send a
POSTrequest tohttps://<casdoor-host>/api/login/oauth/access_token:{
"grant_type": "urn:casdoor:params:oauth:grant-type:verification-code",
"client_id": ClientId,
"username": "+8613800000000",
"code": "123456",
"scope": "openid profile"
}usernameis the phone number or the email address that the code was sent to. For a phone number in the national format, also sendcountry_code.
The grant needs no client secret, so it works from a public client. The response is the same as for the other grants and contains a refresh_token that keeps the user signed in.
Wrong codes count toward the Failed signin limit of the application. Casdoor refuses users who have MFA enabled. Use the authorization code grant for them.
Sign up new users with a verification code
When no user has the phone number or the email address, the grant creates the user, as the sign-up page would, if all of the following conditions hold:
- Enable signup is on for the application, and Disable self signup is off.
- The Signup items of the application require nothing beyond what the code proves. Only ID, Username, Display name, Password, Confirm password, Agreement, Signup button, and Providers may be required, plus
Emailwhen the user signs up with an email address, orPhonewhen the user signs up with a phone number. The default sign-up items require bothEmailandPhone, so make the other one optional. - For a phone number, its region is in the Supported country codes of the organization.
Otherwise, /api/send-verification-code answers that the user doesn't exist, and only existing users can sign in.
Mobile one-click grant
Native apps in mainland China can also sign users in with the phone number of the device, without an SMS code: the one-click login SDK of Alibaba Cloud PNVS returns a token, and the app exchanges it with the grant type urn:casdoor:params:oauth:grant-type:mobile-one-click. See Mobile one-click login.
Client credentials grant
Use this grant for machine-to-machine calls, where no user is present.
-
Turn on the client credentials grant in Grant types of the application.
-
Send a
POSTrequest tohttps://<casdoor-host>/api/login/oauth/access_token:{
"grant_type": "client_credentials",
"client_id": ClientId,
"client_secret": ClientSecret,
} -
Read the token from the response:
{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
Unlike the tokens of the grants above, this access token belongs to the application and not to a user.
Refresh token grant
Use the refresh token from an earlier response to get a new access token.
-
Set the lifetime of refresh tokens in Refresh token expire of the application. The default is 0 hours.
-
Send a
POSTrequest tohttps://<casdoor-host>/api/login/oauth/refresh_token:{
"grant_type": "refresh_token",
"refresh_token": REFRESH_TOKEN,
"scope": SCOPE,
"client_id": ClientId,
"client_secret": ClientSecret,
} -
Read the tokens from the response:
{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
Casdoor checks the refresh request as follows:
- If the token was issued by an authorization code exchange that sent a
client_secret, or by a token exchange, the refresh request must contain the correctclient_secret. Otherwise, Casdoor returnsinvalid_client. A public client that used PKCE without a secret refreshes without one. - The refresh token must belong to the requesting application. Otherwise, Casdoor returns
invalid_grantwiththe token is for wrong application (client_id). - A
scopein the request must be a subset of the original scope. If you omit it, the new token has the original scope. - An unknown or revoked refresh token fails with
invalid_grantandrefresh token is invalid or revoked. A refresh token that Casdoor has invalidated, for example at sign-out, fails withinvalid_grantandrefresh token is expired.
Renaming a user doesn't invalidate the refresh tokens of the user. For the events that do revoke tokens, see When Casdoor revokes tokens.
Refresh token rotation
By default, every refresh returns a new refresh token and revokes the one that was used, as RFC 9700 recommends for public clients. Store the new refresh token after each refresh. A refresh token that was already used fails with invalid_grant.
Rotation breaks clients in which several processes share one refresh token, for example a CLI that runs parallel jobs with a token from an environment variable: the first refresh revokes the token for all the others. For such clients, turn on Disable refresh token rotation in the OIDC/OAuth settings of the application. Then:
- A refresh returns the same refresh token, which keeps its original expiry.
- The access tokens of earlier refreshes stay valid until they expire.
- Signing out still revokes the refresh token for all processes.
Without rotation, a leaked refresh token works until it expires. Keep Refresh token expire short, and prefer DPoP for public clients.
Token exchange grant
Token Exchange (RFC 8693) swaps a token for a new token with different properties. Use it when one service calls another on behalf of a user, or to narrow the scope of a token before you pass it to a downstream service. For example, an API gateway exchanges a token with a broad scope for a token with a narrow scope before it forwards a request to a microservice, so that each service gets only the permissions that it needs.
Send a POST request to https://<casdoor-host>/api/login/oauth/access_token:
{
"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 | Description |
|---|---|
subject_token | The token to exchange, typically an access token or a JSON Web Token (JWT) that you already hold |
subject_token_type | urn:ietf:params:oauth:token-type:access_token (default), urn:ietf:params:oauth:token-type:jwt, or urn:ietf:params:oauth:token-type:id_token |
scope | Optional. A subset of the scope of the subject token. If you omit it, the new token has the scope of the subject token |
audience | Optional. 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 |
The response contains a new token for the same user as the subject token:
{
"access_token": "eyJhb...",
"id_token": "eyJhb...",
"refresh_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid email"
}
Casdoor validates the subject token with the certificate of the application that issued it, which the azp claim identifies, and not with the certificate of the requesting client. If the requesting client isn't the issuer, the aud claim of the subject token must include the client ID of the requesting client. Otherwise, Casdoor rejects the exchange with invalid_grant. This keeps one application from exchanging the tokens of another application without being named as an audience (RFC 8693, section 2.1). The rule applies to every Token format, including JWT-Standard.
Casdoor also refuses the exchange in these cases:
| Case | Error |
|---|---|
The subject token isn't an active token of Casdoor, for example because it was revoked or has expired. With subject_token_type set to urn:ietf:params:oauth:token-type:id_token, Casdoor looks the token up as an ID token, otherwise as an access token | invalid_grant, subject_token is revoked or unknown |
| The subject token has no user, for example a token of the client credentials grant | invalid_grant, subject_token has no user |
| The user is forbidden to sign in | invalid_grant |
| The user isn't in the organization of the requesting application, and the application isn't shared | invalid_grant |
audience isn't a known application | invalid_target |
The audience application isn't in the organization of the user, and isn't shared | invalid_target |
A token of an external issuer can be the subject token too, without a client secret. See Federated credentials.
JWT bearer grant
With the JWT bearer grant (RFC 7523), a client gets an access token by presenting a signed JWT assertion instead of a client secret. Use it for service-to-service calls in which the client holds a private key and you don't want to share a long-lived secret.
-
Turn on JWT Bearer in Grant types of the application.
-
Upload the certificate of the client in Client cert on the Security tab of the application. Casdoor verifies assertions with the public key of that certificate.
-
Create the assertion: a JWT that is signed with the private key of the client and contains the following claims:
Claim Description issIssuer — the client_idof the applicationsubSubject — the client_idof the applicationaudAudience — the Casdoor token endpoint URL expExpiry time (Unix timestamp) -
Send a
POSTrequest tohttps://<casdoor-host>/api/login/oauth/access_token:{
"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"
} -
Read the token from the response:
{
"access_token": "eyJhb...",
"token_type": "Bearer",
"expires_in": 10080,
"scope": "openid"
}
Casdoor verifies the signature and the standard JWT claims. The access token belongs to the application, as with the client credentials grant.
The assertion of the JWT bearer grant can also be a token of an external issuer that the application trusts. See Federated credentials.
Federated credentials (workload identity)
With federated credentials, an application trusts the tokens of an external OpenID Connect issuer, such as GitHub Actions, Kubernetes, a cloud workload identity, or another IdP, as its credential. A workload that already holds such a token gets a Casdoor token without a client secret or a client certificate.
-
In the Casdoor admin console, open the application and go to the OIDC/OAuth tab.
-
In Federated credentials, add a row for each issuer and subject that you trust:
Column Description Issuer The issuer of the external tokens. It must equal the issclaim exactly, for examplehttps://token.actions.githubusercontent.comJWKS URL The URL of the signing keys of the issuer. If you leave it empty, Casdoor reads jwks_urifrom<issuer>/.well-known/openid-configuration, whoseissuermust matchSubject Required. The subclaim to accept.*matches any text, for examplerepo:my-org/my-repo:*Audience The audvalue to accept. If you leave it empty, Casdoor accepts its own origin, its token endpointhttps://<casdoor-host>/api/login/oauth/access_token, or the client ID of the applicationUser The 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 itselfEnable signup Create the mapped user when it doesn't exist yet, on its first sign-in with a token of this issuer. Available only when User is set -
In Grant types, turn on the grant that the workload uses.
-
Click Save.
The workload then presents its external token in one of three ways:
- As
client_assertionat the token endpoint, withclient_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer, to authenticate the client in any grant. Sendclient_idin the request too, because thesubof an external token isn't a client ID. - As the
assertionof the JWT bearer grant. - As the
subject_tokenof the token exchange grant. No client secret is needed.
For example, a GitHub Actions job exchanges its OIDC token for a Casdoor token:
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 verifies an external token as follows:
- The signature is checked with the keys of the issuer. Casdoor caches the keys for one hour, and fetches them again, at most once a minute, when a token has an unknown
kid. - The signing algorithm is one of RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, or EdDSA.
- The token must have an
expclaim. Casdoor allows one minute of clock skew. - A token of a trusted issuer whose subject matches no row fails, for example with
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.
The discovery document lists private_key_jwt in token_endpoint_auth_methods_supported.
Sign users up and in without a Casdoor page
With Enable signup, a service that already verifies your users can give them a Casdoor account and a Casdoor token without showing any Casdoor page. For example, a mobile app signs students in with their school account through its own login service. The login service is an OIDC issuer with a JWKS, and after a successful sign-in it issues a short-lived JWT such as:
{
"iss": "https://login.example.edu",
"sub": "student:2021001",
"aud": "casdoor",
"exp": 1765432100,
"student_id": "2021001",
"name": "Alice",
"email": "alice@example.edu",
"email_verified": true
}
To accept it, add a row with Issuer https://login.example.edu, Subject student:*, Audience casdoor, User {student_id}, and Enable signup on, and turn on JWT Bearer in Grant types. The app or the login service then exchanges the JWT for a Casdoor token:
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
The response has an access token, a refresh token, and an ID token of the user. On the first exchange of a student, Casdoor creates the user as follows:
- The username is the value of the mapped claim. It must be a valid username or an email address, otherwise Casdoor returns
invalid_grantand creates nothing. - The display name comes from
name, the email fromemailandemail_verified, and the avatar frompicture, when the token has them. - The user joins the Default group of the application and gets its Default tag. With signup approval on, the user waits for approval and can't get a token until then.
- Later exchanges with the same claim value sign in the same user. Concurrent first exchanges create one user.
It works even when the application itself doesn't allow signup, because only the trusted issuer can create users this way. It doesn't apply to a shared application.
DPoP (sender-constrained tokens)
Casdoor supports Demonstrating Proof of Possession (DPoP, RFC 9449). DPoP binds an access token to a key that the client holds, so that a leaked token is useless without the private key.
To get a DPoP-bound token, send a DPoP header with a DPoP proof JWT in the token request:
POST /api/login/oauth/access_token
DPoP: <DPoP proof JWT>
Casdoor binds the token to the public key of the proof, by its JWK thumbprint (jkt), and returns the token_type DPoP instead of Bearer:
{
"access_token": "eyJhb...",
"token_type": "DPoP",
"expires_in": 10080,
"scope": "openid"
}
The refresh token request accepts the same DPoP header. Casdoor rejects an invalid proof with the error invalid_dpop_proof. A refresh token that was issued with DPoP is bound to the key too: refreshing it requires a DPoP proof signed with the same key. Without a proof, or with a proof of another key, the refresh fails with invalid_dpop_proof. Casdoor checks the htu claim of a refresh proof against the token endpoint, https://<casdoor-host>/api/login/oauth/access_token.
The discovery document lists the signing algorithms that Casdoor accepts for proofs in dpop_signing_alg_values_supported:
{
"dpop_signing_alg_values_supported": ["RS256", "RS512", "ES256", "ES384", "ES512", "PS256", "PS384", "PS512"]
}
The token introspection response shows the key binding in the cnf.jkt claim (RFC 9449, section 8).
Verify an access token
Casdoor supports token introspection (RFC 7662). Authenticate the request with HTTP Basic authentication, with the client ID as the username and the client secret as the password:
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
Example response:
{
"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"
}
Alternatively, verify the signature of the token yourself with the public key of the application's certificate, or with the keys of the JWKS endpoint. The SDKs do this in ParseJwtToken().
Revoke a token
Casdoor supports token revocation (RFC 7009). Send a POST request with form parameters:
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
| Parameter | Required | Description |
|---|---|---|
token | Yes | The access token or the refresh token to revoke |
token_type_hint | No | access_token or refresh_token. Casdoor looks the token up as this type first, then as the other type |
client_id | Yes | The client ID of the application. Send it with HTTP Basic authentication or as a form parameter |
client_secret | See description | The client secret of the application. Required for tokens issued by the authorization code grant without PKCE, the client credentials grant and the token exchange grant. Public clients that used PKCE can send only client_id |
The access token and the refresh token of one grant are revoked together. If the refresh token is shared by several access tokens, because refresh token rotation is off, all of them are revoked. Casdoor returns HTTP 200 with an empty body when the token is revoked, already expired, unknown, or belongs to another application. A missing client_id, an unknown client or a wrong client secret returns HTTP 401 with invalid_client, and a missing token returns HTTP 400 with invalid_request.
Use an access token
Send the access token to call the Casdoor API. For example, call /api/userinfo, with GET or POST, in one of two ways:
- With the
Authorizationheader:Authorization: Bearer <access-token> - With a query parameter:
https://<casdoor-host>/api/userinfo?accessToken=<access-token>
Casdoor returns the fields of the user that the scope of the token allows:
{
"sub": "7a6b4a8a-b731-48da-bc44-36ae27338817",
"iss": "http://localhost:8000",
"aud": "c58c..."
}
To get more fields, request more scopes in the authorization request.
UserInfo and get-account
| Endpoint | Returns |
|---|---|
/api/userinfo | The standard OpenID Connect (OIDC) claims of the user, limited by the scopes of the token |
/api/get-account | The complete user object of the signed-in account. This endpoint is specific to Casdoor. It includes the access token of the external OAuth provider, if there is one |
Get the access token of an external provider
When a user signs in through an external OAuth provider, such as GitHub or Google, Casdoor stores the access token of that provider in the originalToken field of the user. Your application can use it to call the API of the provider, such as the GitHub API or the Google Drive API, on behalf of the user, without another OAuth flow.
Read the token from /api/get-account:
{
"status": "ok",
"data": {
"name": "user123",
"originalToken": "ya29.a0AfH6SMBx...",
...
}
}
Casdoor returns originalToken only to the user and to administrators. For all other requesters, it masks the field.