Pular para o conteúdo principal

OAuth 2.0

Introdução

O Casdoor suporta o uso de Access Token para autenticar clientes. Nesta seção, mostraremos como obter um Access Token, como verificar um Access Token e como usar um Access Token.

Como Obter um Access Token

Há duas maneiras de obter um Access Token: você pode usar os SDKs do Casdoor. Para informações detalhadas, por favor consulte a documentação do SDK. Aqui, mostraremos principalmente como usar a API para obter o Access Token.

Casdoor supports standard OAuth 2.0 grant types including Authorization Code Grant, Implicit Grant, Resource Owner Password Credentials Grant, Client Credentials Grant, Refresh Token, Device Authorization Grant, and Token Exchange.

Por razões de segurança, o aplicativo Casdoor tem o modo de código de autorização ativado por padrão. Se você precisa usar outros modos, por favor vá ao aplicativo apropriado para configurá-lo.

Tipos de Concessão

Authorization Code Grant

Primeiro, redirecione seus usuários para:

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

Escopos Disponíveis

NomeDescrição
openid (no scope)sub (id do usuário), iss (emissor) e aud (audiência)
profileinformações do perfil do usuário, incluindo nome, displayName e avatar
emailendereço de email do usuário
addressendereço do usuário
phonenúmero de telefone do usuário
informação

Sua Aplicação OAuth pode solicitar os escopos no redirecionamento inicial. Você pode especificar múltiplos escopos separando-os com um espaço usando %20:

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

Para mais detalhes, por favor veja o padrão OIDC

Após seu usuário se autenticar com o Casdoor, o Casdoor irá redirecioná-lo para:

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

Agora que você obteve o código de autorização, faça uma solicitação POST para:

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

na sua aplicação backend:

{
"grant_type": "authorization_code",
"client_id": ClientId,
"client_secret": ClientSecret,
"code": Code,
}

Você receberá a seguinte resposta:

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

Casdoor supports PKCE (Proof Key for Code Exchange) for enhanced security. To enable PKCE, add two parameters when requesting the authorization code:

&code_challenge_method=S256&code_challenge=YOUR_CHALLENGE

The code challenge should be a Base64-URL-encoded SHA-256 hash of your randomly generated code verifier (43-128 characters). When requesting the token, include the original code_verifier parameter. With PKCE enabled, client_secret becomes optional, but if provided, it must be correct.

For OAuth providers configured in Casdoor (like Twitter and custom providers with PKCE enabled), Casdoor automatically generates unique code verifiers for each authentication flow, so you don't need to manually implement PKCE.

Binding Tokens to Specific Services

When your application needs to call multiple backend services, you might want tokens that are explicitly bound to a specific service. This prevents security issues where a token meant for one service could accidentally be used with another.

Casdoor supports RFC 8707 Resource Indicators, which lets you specify the intended service when requesting authorization. Add the resource parameter with an absolute URI identifying your service:

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

When you exchange the authorization code for tokens, include the same resource parameter:

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

The resulting access token will have its aud (audience) claim set to your resource URI instead of the client ID. Your backend service can then verify that tokens were issued specifically for it by checking the audience claim. The resource must match exactly between the authorization and token requests.

Signup Flow with OAuth

When users sign up through the OAuth authorization flow, they are automatically redirected to your application's callback URL with the authorization code, just like the sign-in flow. Previously, users had to manually click through intermediate pages after creating their account. Now the signup process matches the streamlined experience of signing in—once registration completes, Casdoor immediately generates the authorization code and redirects to your redirect_uri.

Your application doesn't need any changes to support this. The authorization parameters (client_id, response_type, redirect_uri, etc.) are automatically passed through the signup process when users choose to create a new account during OAuth authorization.

Implicit Grant

Talvez sua aplicação não tenha um backend, e você precise usar Implicit Grant. Primeiro, você precisa ter certeza de que o Implicit Grant está habilitado, então redirecione seus usuários para:

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

Após seu usuário se autenticar com o Casdoor, o Casdoor irá redirecioná-lo para:

https://REDIRECT_URI/#access_token=ACCESS_TOKEN

O Casdoor também suporta o id_token como response_type, que é um recurso do OpenID.

Device Grant

Maybe your devices have limited input capabilities or lack a suitable browser, and you need to use Device Grant. First, you need to make sure you have Device Grant enabled, the request device_authorization_endpoint in OIDC discover, then use QR code or text to show verification_uri and lead user to enter login page.

Second, you should request token endpoint to get Access Token with parameter define in rfc8628.

Resource Owner Password Credentials Grant

Se sua aplicação não tem um frontend que redireciona os usuários para o Casdoor, então você pode precisar disso.

Primeiro, você precisa ter certeza de que o Password Credentials Grant está habilitado e enviar uma solicitação POST para:

https://<CASDOOR_HOST>/api/login/oauth/access_token
{
"grant_type": "password",
"client_id": ClientId,
"client_secret": ClientSecret,
"username": Username,
"password": Password,
}

You will get the following response:

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

Client Credentials Grant

Você também pode usar Client Credentials Grant quando sua aplicação não tem um frontend.

Primeiro, você precisa ter certeza de que o Client Credentials Grant está habilitado e enviar uma solicitação POST para https://<CASDOOR_HOST>/api/login/oauth/access_token:

{
"grant_type": "client_credentials",
"client_id": ClientId,
"client_secret": ClientSecret,
}

Você receberá a seguinte resposta:

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

É importante notar que o AccessToken obtido desta forma difere dos três primeiros, pois corresponde à aplicação e não ao usuário.

Refresh Token

Talvez você queira atualizar seu Access Token, então você pode usar o refreshToken que obteve acima.

Primeiro, você precisa definir o tempo de expiração do Refresh Token no aplicativo (padrão é 0 horas), e enviar uma solicitação POST para https://<CASDOOR_HOST>/api/login/oauth/refresh_token

{
"grant_type": "refresh_token",
"refresh_token": REFRESH_TOKEN,
"scope": SCOPE,
"client_id": ClientId,
"client_secret": ClientSecret,
}

Você receberá uma resposta como esta:

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

Token Exchange Grant

Token Exchange (RFC 8693) lets you swap an existing token for a new one with different characteristics—particularly useful when one service needs to call another on behalf of a user, or when you need to narrow down a token's scope for a specific downstream service.

To exchange a token, 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"
}

The subject_token is the token you want to exchange—typically an access token or JWT you already have. If you want to narrow the permissions in the new token, specify a scope that's a subset of the original token's scope. When you omit scope, the new token inherits the same scope as the subject token.

Casdoor supports three token types for subject_token_type:

  • urn:ietf:params:oauth:token-type:access_token (default)
  • urn:ietf:params:oauth:token-type:jwt
  • urn:ietf:params:oauth:token-type:id_token

The response returns a new token tied to the same user as your subject token:

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

For example, an API gateway might exchange a broad-scoped access token for a narrower one before forwarding requests to a downstream microservice. This pattern—called scope downscoping—ensures each service gets only the permissions it needs, rather than inheriting full access from the original token.

Como Verificar Access Token

O Casdoor atualmente suporta o endpoint de introspecção de token. Este endpoint é protegido por Autenticação Básica (ClientId:ClientSecret).

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

Você receberá a seguinte resposta:

{
"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"
}

Como Usar AccessToken

Você pode usar AccessToken para acessar APIs do Casdoor que requerem autenticação.

Por exemplo, existem duas maneiras diferentes de solicitar /api/userinfo.

Tipo 1: Parâmetro de consulta

https://<CASDOOR_HOST>/api/userinfo?accessToken=<your_access_token>

Tipo 2: Token Bearer HTTP

https://<CASDOOR_HOST>/api/userinfo with the header: "Authorization: Bearer <your_access_token>"

O Casdoor irá analisar o access_token e retornar as informações do usuário correspondentes de acordo com o scope. Você receberá a mesma resposta, que se parece com isto:

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

Se você espera mais informações do usuário, adicione scope ao obter o AccessToken na etapa Authorization Code Grant.

Accessing OAuth Provider Tokens

When users authenticate through OAuth providers (GitHub, Google, etc.), you can access the provider's original access token to make API calls to the third-party service on their behalf. This token is stored in the user's originalToken field.

The token is available through the /api/get-account endpoint:

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

The originalToken is visible only when the user requests their own account or when the requester is an admin. For other requests, it is masked for privacy.

This allows your application to interact with third-party APIs (e.g., GitHub API, Google Drive API) using the provider's access token without requiring additional OAuth flows.

Diferenças entre as APIs userinfo e get-account

  • /api/userinfo: Esta API retorna informações do usuário como parte do protocolo OIDC. Ela fornece informações limitadas, incluindo apenas as informações básicas definidas nos padrões OIDC. Para uma lista de escopos disponíveis suportados pelo Casdoor, por favor consulte a seção de escopos disponíveis.

  • /api/get-account: Esta API recupera o objeto do usuário para a conta atualmente logada. It is a Casdoor-specific API that allows you to obtain all the information of the user in Casdoor, including the OAuth provider's access token when applicable.