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 APIadicional. Você pode gerar e distribuir umJWTde qualquer maneira. O API Gateway apenas autentica oJWTusando umapublic key JWK.Suporta
JWKsque não contêm umkid.Permite configurar múltiplos
JWKs.Permite ler tokens diretamente do
headerou daquery. 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
JWTfor transmitido comoAuthorization bearer {token}, configureparameter: AuthorizationeparameterLocation: headerpara ler o token corretamente.Adicione a configuração
preventJtiReplay: truee ative verificações anti-replay com base noclaim:jti.Adicione a configuração
bypassEmptyToken: truepara ignorar a verificação e encaminhar a requisição diretamente ao backend caso o token não exista.Adicione a configuração
ignoreExpirationCheck: truepara ignorar a verificação de expiraçãoexpdo 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 apublic key. Mantenha suaprivate keysegura. O plug-in de autenticação JWT oferece suporte aos seguintes algoritmos:
|
Algoritmo de assinatura |
Valores de |
|
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 |
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-inlê o valor do JWT com base noparametereparameterLocationconfigurados. Por exemplo,parameter: X-TokeneparameterLocation: headerindicam que o JWT é lido do cabeçalhoX-Tokenda requisição.Caso a API tenha um parâmetro com o mesmo nome do
parameter, omita oparameterLocation. Caso contrário, um erro será reportado durante a chamada.Se utilizar o cabeçalho Authorization para transmitir o token, como
Authorization bearer {token}, configureparameter: AuthorizationeparameterLocation: header. Assim, o plug-in JWT lerá o valor do token corretamente.Com
preventJtiReplay: trueconfigurado, o plug-in usa o campojtinosclaimspara executar uma verificação anti-replay.Com
bypassEmptyToken: trueconfigurado, se o parâmetro do token estiver vazio, a verificação é ignorada e a requisição é encaminhada diretamente ao backend.Com
ignoreExpirationCheck: trueconfigurado, a verificação de expiraçãoexpé ignorada. Caso contrário, o gateway verifica se o token expirou.-
Para que o API Gateway encaminhe os
claimsdo token à aplicação backend, configure os parâmetros de encaminhamento por meio do campotokenParameters.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,patheformData.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 oparameter mappingfor utilizado e o corpo da requisição estiver no formatoform.
-
Configure uma única chave no campo
jwkou múltiplas chaves no campojwks.É permitida apenas uma chave sem o campo
kid.É possível configurar múltiplas chaves que contenham um
kid, mas cadakiddeve ser único.
3. Regras de verificação
O plug-in usa o
parametere oparameterTokenconfigurados para obter um token. Para encaminhar requisições ao backend quando não houver um token disponível, configurebypassEmptyToken: true.-
Ao configurar múltiplas chaves, a seleção obedece às seguintes regras:
A chave com um
kidcorrespondente ao do token da requisição tem prioridade na verificação de assinatura.Apenas uma chave sem
kidpode ser configurada. Se nenhuma chave com umkidcorrespondente for encontrada, a chave semkidserá usada para a verificação de assinatura.Se nenhuma chave sem
kidestiver configurada e o token da requisição não contiver umkid, ou se nenhuma chave for correspondida pelokid, o erroA403JKserá reportado.
Caso o token contenha os campos
iat,nbfouexp, 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
expdo token. Para ignorar a verificação de expiraçãoexp, configureignoreExpirationCheck: true.Se o campo
tokenParametersestiver configurado para encaminhamento, um campoclaimserá enviado ao backend caso esteja presente nosclaimsdo token. Umclaimausente 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
Faça login no API Gateway console. No painel de navegação à esquerda, clique em .
Na página Plug-ins, clique em Plug-in Datasets.
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.
-
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.
ImportanteAo 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.
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 |
Quando o recurso anti-replay está configurado no |
|
403 |
S403JU |
Claim |
Quando o recurso anti-replay está configurado no |
|
403 |
A403JT |
Invalid JWT: ${Reason} |
O |
|
400 |
I400JD |
JWT Deserialize Failed: |
O |
|
403 |
A403JK |
No matching JWK, |
Nenhum |
|
403 |
A403JE |
JWT is expired at |
O |
|
400 |
I400JP |
Invalid JWT plugin config: ${JWT} |
O plug-in de |
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
claimNameeparameterNamepodem ter até 32 caracteres e conter apenas letras, dígitos, hifens (-) e sublinhados (_).O
algpara JWKs oferece suporte aos seguintes algoritmos: RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384 e HS512.