Todos os produtos
Search
Central de documentação

API Gateway:JWT authentication plug-in

Última atualização: Sep 21, 2026

O JSON Web Token (JWT), conforme definido em RFC7519, oferece uma solução prática para os gateways autenticarem requisições. O API Gateway pode hospedar a public JWK do usuário para autenticar requisições via JWT e encaminhar os claims para o backend como parâmetros. Isso simplifica o desenvolvimento de aplicações backend. Este tópico descreve como configurar o plug-in de autenticação JWT. Para obter mais informações sobre o processo de autenticação de token JWT e conceitos básicos, consulte JWT-based token authentication.

O JWT authentication plug-in agora implementa o recurso OpenId Connect, antes configurado na API. Recomendamos o uso do plug-in de JWT authentication. O plug-in de JWT authentication oferece as seguintes vantagens em relação à autenticação OpenId Connect configurada em uma API:

  • Não é preciso configurar uma authorization API adicional. Você pode gerar e distribuir um JWT de qualquer maneira. O API Gateway apenas autentica o JWT usando uma public key JWK.

  • Suporta JWKs que não contêm um kid.

  • Permite configurar múltiplos JWKs.

  • Permite ler tokens diretamente do header ou da query. Não é necessário definir um parâmetro de token para cada API.

  • Permite ler tokens a partir de um campo no cabeçalho de cookie da requisição.

  • Se um JWT for transmitido como Authorization bearer {token}, configure parameter: Authorization e parameterLocation: header para ler o token corretamente.

  • Adicione a configuração preventJtiReplay: true e ative verificações anti-replay com base no claim:jti.

  • Adicione a configuração bypassEmptyToken: true para ignorar a verificação e encaminhar a requisição diretamente ao backend caso o token não exista.

  • Adicione a configuração ignoreExpirationCheck: true para ignorar a verificação de expiração exp do token.

Caso você configure um JWT authentication plug-in e o vincule a uma API com o recurso OpenID Connect já configurado, as definições do plug-in sobrescreverão a configuração do OpenID Connect na API.

1. Obter um JWK (Json Web Key)

O plug-in de autenticação JWT usa JSON Web Keys (JWK), conforme definidas em RFC7517, para assinar e autenticar JWTs. Para configurar um JWT authentication plug-in, gere primeiro uma JSON Web Key válida. É possível gerar a chave por conta própria ou usar uma ferramenta online JSON Web Key Generator, como https://tools.top/jwt-encode.html. Veja a seguir um exemplo de JSON Web Key válida. Use a chave privada para assinar o token e configure a chave pública no plug-in de JWT authentication para autenticá-lo. Um JWK válido tem o seguinte formato:

{
  "kty": "RSA",
  "e": "AQAB",
  "kid": "O9fpdhrViq2zaaaBEWZITz",
  "use": "sig",
  "alg": "RS256",
  "n": "qSVxcknOm0uCq5vGsOmaorPDzHUubBmZZ4UXj-9do7w9X1uKFXAnqfto4TepSNuYU2bA_-tzSLAGBsR-BqvT6w9SjxakeiyQpVmexxnDw5WZwpWenUAcYrfSPEoNU-0hAQwFYgqZwJQMN8ptxkd0170PFauwACOx4Hfr-9FPGy8NCoIO4MfLXzJ3mJ7xqgIZp3NIOGXz-GIAbCf13ii7kSStpYqN3L_zzpvXUAos1FJ9IPXRV84tIZpFVh2lmRh0h8ImK-vI42dwlD_hOIzayL1Xno2R0T-d5AwTSdnep7g-Fwu8-sj4cCRWq3bd61Zs2QOJ8iustH0vSRMYdP5oYQ"
}        

Este exemplo apresenta o formato JSON. Caso utilize YAML para configurar o plug-in, converta a chave para o formato YAML.

  • Em um JWT authentication plug-in, configure apenas a public key. Mantenha sua private key segura. O plug-in de autenticação JWT oferece suporte aos seguintes algoritmos:

Algoritmo de assinatura

Valores de alg suportados

RSASSA-PKCS1-V1_5 com SHA-2

RS256, RS384, RS512

Curva Elíptica (ECDSA) com SHA-2

ES256, ES384, ES512

HMAC usando SHA-2

HS256, HS384, HS512

Importante

Ao configurar uma chave do tipo HS256, HS384 ou HS512, ela deve ser um valor codificado em Base64 URL. Caso encontre o erro "Invalid Signature", verifique se o formato da sua chave é consistente com a chave usada para gerar o token.

2. Configuração do plug-in

Configure o plug-in no formato JSON ou YAML. Ambos os formatos compartilham o mesmo schema. Utilize uma ferramenta de conversão de YAML to JSON para alternar entre eles. O código a seguir apresenta um modelo no formato YAML.

---
parameter: X-Token           # The parameter from which the JWT is retrieved. This corresponds to an API parameter. 
parameterLocation: header    # The location from which the JWT is retrieved. Supported values: query and header. This parameter is optional if the API request mode is mapping. This parameter is required if the API request mode is pass-through.
preventJtiReplay: false      # Specifies whether to enable the anti-replay check for jti. Default value: false.
bypassEmptyToken: false      # Specifies whether to skip verification and forward the request to the backend when the token is empty.
ignoreExpirationCheck: false # Specifies whether to ignore the check for the exp expiration time.
orAppAuth: false             # Default value: false. Both Alibaba Cloud APP authentication and the JWT plug-in are verified. If this is set to true, if one authentication method passes, the other is skipped.
claimParameters:             # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud             # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud       # The name of the mapped parameter.
  location: header           # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId          # The name of the claim. Public and private claims are supported.
  parameterName: userId      # The name of the mapped parameter.
  location: query            # The location of the mapped parameter. Supported values: query, header, path, and formData.
#
# The Public Key of the JSON Web Key.
jwk:
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5vGsOmaorPDzHUubBmZZ4UXj-9do7w9X1uKFXAnqfto4TepSNuYU2bA_-tzSLAGBsR-BqvT6w9SjxakeiyQpVmexxnDw5WZwpWenUAcYrfSPEoNU-0hAQwFYgqZwJQMN8ptxkd0170PFauwACOx4Hfr-9FPGy8NCoIO4MfLXzJ3mJ7xqgIZp3NIOGXz-GIAbCf13ii7kSStpYqN3L_zzpvXUAos1FJ9IPXRV84tIZpFVh2lmRh0h8ImK-vI42dwlD_hOIzayL1Xno2R0T-d5AwTSdnep7g-Fwu8-sj4cCRWq3bd61Zs2QOJ8iustH0vSRMYdP5oYQ
#
# You can configure multiple JWKs. This can be configured together with the jwk field.
# When you configure multiple JWKs, kid is required. If the JWT does not provide a kid, verification fails.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz         # When only one JWK is configured, kid is optional. However, if the JWT contains a kid, the gateway verifies the consistency of the kid.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz         # When only one JWK is configured, kid is optional. However, if the JWT contains a kid, the gateway verifies the consistency of the kid.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v...                
  • O JWT authentication plug-in lê o valor do JWT com base no parameter e parameterLocation configurados. Por exemplo, parameter: X-Token e parameterLocation: header indicam que o JWT é lido do cabeçalho X-Token da requisição.

  • Caso a API tenha um parâmetro com o mesmo nome do parameter, omita o parameterLocation. Caso contrário, um erro será reportado durante a chamada.

  • Se utilizar o cabeçalho Authorization para transmitir o token, como Authorization bearer {token}, configure parameter: Authorization e parameterLocation: header. Assim, o plug-in JWT lerá o valor do token corretamente.

  • Com preventJtiReplay: true configurado, o plug-in usa o campo jti nos claims para executar uma verificação anti-replay.

  • Com bypassEmptyToken: true configurado, se o parâmetro do token estiver vazio, a verificação é ignorada e a requisição é encaminhada diretamente ao backend.

  • Com ignoreExpirationCheck: true configurado, a verificação de expiração exp é ignorada. Caso contrário, o gateway verifica se o token expirou.

  • Para que o API Gateway encaminhe os claims do token à aplicação backend, configure os parâmetros de encaminhamento por meio do campo tokenParameters.

    • claimName: O nome do claim no token.

    • parameterName: O nome do parâmetro encaminhado para o backend.

    • location: A localização do parâmetro encaminhado para o backend. Valores aceitos: header, query, path e formData.

      • Caso defina como path, o caminho do backend deve conter um parâmetro com o mesmo nome, como /path/{userId}.

      • Caso defina como formData, o claim só será mapeado corretamente para o formulário do backend quando o parameter mapping for utilizado e o corpo da requisição estiver no formato form.

  • Configure uma única chave no campo jwk ou múltiplas chaves no campo jwks.

    • É permitida apenas uma chave sem o campo kid.

    • É possível configurar múltiplas chaves que contenham um kid, mas cada kid deve ser único.

3. Regras de verificação

  • O plug-in usa o parameter e o parameterToken configurados para obter um token. Para encaminhar requisições ao backend quando não houver um token disponível, configure bypassEmptyToken: true.

  • Ao configurar múltiplas chaves, a seleção obedece às seguintes regras:

    • A chave com um kid correspondente ao do token da requisição tem prioridade na verificação de assinatura.

    • Apenas uma chave sem kid pode ser configurada. Se nenhuma chave com um kid correspondente for encontrada, a chave sem kid será usada para a verificação de assinatura.

    • Se nenhuma chave sem kid estiver configurada e o token da requisição não contiver um kid, ou se nenhuma chave for correspondida pelo kid, o erro A403JK será reportado.

  • Caso o token contenha os campos iat, nbf ou exp, o plug-in JWT verifica a validade desses campos de tempo. A unidade de tempo é o segundo (s).

  • Por padrão, o API Gateway verifica o campo de tempo de expiração exp do token. Para ignorar a verificação de expiração exp, configure ignoreExpirationCheck: true.

  • Se o campo tokenParameters estiver configurado para encaminhamento, um campo claim será enviado ao backend caso esteja presente nos claims do token. Um claim ausente não será encaminhado.

4. Usar conjuntos de dados de plug-in com o plug-in de autenticação JWT

4.1 Crie um conjunto de dados do plug-in de autenticação JWT

  1. Faça login no API Gateway console. No painel de navegação à esquerda, clique em API Management > Plug-in Management.

  2. Na página Plug-ins, clique em Plug-in Datasets.

  3. No canto superior direito, clique em Create Dataset. Na caixa de diálogo exibida, insira um Name personalizado, defina o Type como JWT_JWK_LIST e clique em OK e crie o conjunto de dados.

  4. Acesse o conjunto de dados criado. No canto superior direito, clique em Create Dataset Entry. No campo Data Value, configure o JWK compatível com o plug-in de autenticação JWT. No campo Expiration Time, configure o período de validade da chave pública.

    Importante

    Ao configurar múltiplos JWKs, use um kid diferente para cada JWK. Os valores de dados do JWK devem ser configurados na ordem mostrada no exemplo a seguir.

    kty: RSA
    e: AQAB
    use: sig
    kid: N3h666
    alg: RS256
    n: qfzaxmlnl...

4.2 Exemplo de configuração de um conjunto de dados de plug-in para o plug-in de autenticação JWT

---
parameter: X-Token         # The parameter from which the JWT is retrieved. This corresponds to an API parameter.
parameterLocation: header  # The location from which the JWT is retrieved. Supported values: query and header. This parameter is optional if the API request mode is mapping. This parameter is required if the API request mode is pass-through.
claimParameters:           # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud           # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud     # The name of the mapped parameter.
  location: header         # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId        # The name of the claim. Public and private claims are supported.
  parameterName: userId    # The name of the mapped parameter.
  location: query          # The location of the mapped parameter. Supported values: query, header, path, and formData.
preventJtiReplay: false    # Specifies whether to enable the anti-replay check for jti. Default value: false.
ignoreExpirationCheck: true  # Specifies whether to ignore the check for the exp expiration time.
jwkListDataSet: cb4f000b6b8244329ac25XXXc8a4f9d6  # The ID of the plug-in dataset.
Nota

Caso a configuração não entre em vigor, envie um ticket para atualizar sua instância.

5. Exemplos de configuração

5.1. Configure um único JWK

---
parameter: X-Token         # The parameter from which the JWT is retrieved. This corresponds to an API parameter.
parameterLocation: header  # The location from which the JWT is retrieved. Supported values: query and header. This parameter is optional if the API request mode is mapping. This parameter is required if the API request mode is pass-through.
claimParameters:           # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud           # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud     # The name of the mapped parameter.
  location: header         # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId        # The name of the claim. Public and private claims are supported.
  parameterName: userId    # The name of the mapped parameter.
  location: query          # The location of the mapped parameter. Supported values: query, header, path, and formData.
preventJtiReplay: false    # Specifies whether to enable the anti-replay check for jti. Default value: false.
#
# The Public Key of the JSON Web Key.
jwk:
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5vGsOmaorPDzHUubBmZZ4UXj-9do7w9X1uKFXAnqfto4TepSNuYU2bA_-tzSLAGBsR-BqvT6w9SjxakeiyQpVmexxnDw5WZwpWenUAcYrfSPEoNU-0hAQwFYgqZwJQMN8ptxkd0170PFauwACOx4Hfr-9FPGy8NCoIO4MfLXzJ3mJ7xqgIZp3NIOGXz-GIAbCf13ii7kSStpYqN3L_zzpvXUAos1FJ9IPXRV84tIZpFVh2lmRh0h8ImK-vI42dwlD_hOIzayL1Xno2R0T-d5AwTSdnep7g-Fwu8-sj4cCRWq3bd61Zs2QOJ8iustH0vSRMYdP5oYQ
                        

5.2. Configure múltiplos JWKs

---
parameter: Authorization   # Get the token from the Authorization header. 
parameterLocation: header  # Get the token from the Authorization header.
claimParameters:           # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud           # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud     # The name of the mapped parameter.
  location: header         # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId        # The name of the claim. Public and private claims are supported.
  parameterName: userId    # The name of the mapped parameter.
  location: query          # The location of the mapped parameter. Supported values: query, header, path, and formData.
preventJtiReplay: true     # Specifies whether to enable the anti-replay check for jti. Default value: false.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz         # When you configure multiple JWKs, you must use different kids.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz         # When you configure multiple JWKs, you must use different kids.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v...

5.3. Ler um token de um campo no cookie da requisição

---
parameter: cookie         # The parameter from which the JWT is retrieved. This corresponds to an API parameter.
parameterLocation: header  # The location from which the JWT is retrieved. Supported values: query and header. This parameter is optional if the API request mode is mapping. This parameter is required if the API request mode is pass-through.
parameterSection: token    # For example, the value of the cookie is username=tom ; token=abcsef
claimParameters:           # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud           # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud     # The name of the mapped parameter.
  location: header         # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId        # The name of the claim. Public and private claims are supported.
  parameterName: userId    # The name of the mapped parameter.
  location: query          # The location of the mapped parameter. Supported values: query, header, path, and formData.
preventJtiReplay: true     # Specifies whether to enable the anti-replay check for jti. Default value: false.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz         # When you configure multiple JWKs, you must use different kids.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz         # When you configure multiple JWKs, you must use different kids.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v...

Em alguns cenários web, por motivos de segurança, salve um token em um campo específico de um cookie. O plug-in JWT do API Gateway permite ler um token a partir de um campo no cookie da requisição. Especifique o nome do campo usando o parâmetro parameterSection. Por exemplo, se o cabeçalho de cookie da requisição for o seguinte, o API Gateway poderá extrair o token do cookie.

Cookie: acw_tc=123; token=0QzRCMDBBQUYwRjE1MjYxQzU0QjY4NEM5MTc1NTQ1OUVCOTIzNzA4RDk3MDg5MzlDOTMQTVENDZCRUI1NkYyMEUyO; csrf=073957d8d2823be4f6c0cad23c764558

5.4 Configure uma lista de bloqueios

A lista de bloqueios no plug-in de autenticação JWT barra requisições de usuários que, mesmo com um token válido, foram posteriormente adicionados à lista. Nesse cenário, o plug-in de autenticação JWT do API Gateway, em conjunto com o recurso de conjunto de dados de plug-in, rejeita requisições com base nos parâmetros de claim descriptografados do token. O API Gateway não apenas rejeita requisições que atendem às condições de bloqueio, mas também permite personalizar a resposta de rejeição. O código a seguir demonstra essa configuração. Observe todas as definições de parâmetros que começam com block:

---
parameter: Authorization   # Get the token from the Authorization header. 
parameterLocation: header  # Get the token from the Authorization header.
claimParameters:           # Claim parameter transformation. The gateway maps JWT claims to backend parameters.
- claimName: aud           # The name of the claim. Public and private claims are supported.
  parameterName: X-Aud     # The name of the mapped parameter.
  location: header         # The location of the mapped parameter. Supported values: query, header, path, and formData.
- claimName: userId        # The name of the claim. Public and private claims are supported.
  parameterName: userId    # The name of the mapped parameter.
  location: query          # The location of the mapped parameter. Supported values: query, header, path, and formData.
blockClaimParameterName: userId  # This parameter is used as the condition for the blacklist logic. If the value of this parameter is in the blockByDataSet dataset, the request is blocked.
blockByDataSet: 87b65008e92541938537b1a4a236eda5  # The blacklist dataset.
blockStatusCode: 403       # The status code of the response for a rejected request.
blockResponseHeaders:      # The header of the response for a rejected request.
  Content-Type: application/xml
blockResponseBody:         # The body of the response for a rejected request.
  <Reason>be blocked</Reason>
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz         # When you configure multiple JWKs, you must use different kids.
  kty: RSA
  e: AQAB
  use: sig
  alg: RS256
  n: qSVxcknOm0uCq5v....

6. Códigos de erro relacionados

Status

Código

Mensagem

Descrição

400

I400JR

JWT required

O parâmetro JWT não foi encontrado.

403

S403JI

Claim jti is required when preventJtiReplay:true

Quando o recurso anti-replay está configurado no JWT authorization plugin, a requisição não fornece um jti válido.

403

S403JU

Claim jti in JWT is used

Quando o recurso anti-replay está configurado no JWT authorization plugin, o jti na requisição já foi utilizado.

403

A403JT

Invalid JWT: ${Reason}

O JWT fornecido na requisição é inválido.

400

I400JD

JWT Deserialize Failed: ${Token}

O JWT fornecido na requisição não pôde ser analisado.

403

A403JK

No matching JWK, kid:${kid} not found

Nenhum JWK correspondente foi encontrado para o kid no JWT da requisição.

403

A403JE

JWT is expired at ${Date}

O JWT fornecido na requisição expirou.

400

I400JP

Invalid JWT plugin config: ${JWT}

O plug-in de JWT authentication está configurado incorretamente.

Caso um código de resposta inesperado seja retornado, verifique o cabeçalho X-Ca-Error-Code para o ErrorCode e o cabeçalho X-Ca-Error-Message para o ErrorMessage. Se o código de erro A403JT ou I400JD for retornado, acesse jwt.io para verificar a validade e o formato do seu token.

7. Limites

  • O tamanho dos metadados do plug-in não pode exceder 50 KB.

  • É possível encaminhar no máximo 16 parâmetros. Os valores de claimName e parameterName podem ter até 32 caracteres e conter apenas letras, dígitos, hifens (-) e sublinhados (_).

  • O alg para JWKs oferece suporte aos seguintes algoritmos: RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384 e HS512.