O JSON Web Token (JWT), em conformidade com a RFC 7519, é um método prático usado pelo API Gateway para autenticar requisições. O API Gateway armazena as public JSON Web Keys (JWKs) dos usuários e usa essas JWKs para assinar e autenticar os JWTs nas requisições. Em seguida, o API Gateway encaminha os parâmetros de claim aos serviços de backend como parâmetros de backend, simplificando o desenvolvimento das aplicações de backend. Este tópico descreve como configurar um plug-in de autenticação JWT. Para obter mais informações sobre o JWT e o processo de autenticação, consulte Autenticação de token baseada em JWT.
Os plug-ins de autenticação JWT oferecem as mesmas funções do OpenID Connect e trazem os seguintes benefícios:
Não é necessário configurar uma
operação de API de autorizaçãoadicional. OsJWTspodem ser gerados e distribuídos de várias formas. O API Gateway responsabiliza-se apenas pela autenticação doJWTpor meio dasJWKs públicas.Há suporte para
JWKssemkidespecificado.É possível configurar múltiplas
JWKs.Leia as informações do token a partir do parâmetro de
headerouqueryda requisição.Também é possível ler o token do header Cookie em uma requisição usando um plug-in de autenticação JWT.
Para transmitir um
JWTem um header Authorization, comoAuthorization bearer {token}, definaparametercomo Authorization eparameterLocationcomo header. Assim, as informações do token serão lidas corretamente.A verificação anti-replay baseada na claim
jtitem suporte quandopreventJtiReplayé definido como true.Requisições sem tokens podem ser encaminhadas aos serviços de backend sem verificação se
bypassEmptyTokenfor definido como true.Ignore a verificação da configuração
expdos tokens ao definirignoreExpirationCheckcomo true.
Se você configurar um plug-in de autenticação JWT e vinculá-lo a uma API que já tenha o recurso OpenID Connect configurado, o plug-in de autenticação JWT prevalecerá sobre o recurso OpenID Connect.
1. Obter uma JWK
JWKs compatíveis com a RFC 7517 são usadas para assinar e autenticar JWTs. Para configurar um plug-in de autenticação JWT, gere uma JWK válida manualmente ou use um gerador de JWK online, como mkjwk.org. O exemplo a seguir mostra uma JWK válida. Neste exemplo, a chave privada assina o token, enquanto a chave pública é configurada no plug-in de autenticação JWT para autenticar a assinatura.
{
"kty": "RSA",
"e": "AQAB",
"kid": "O9fpdhrViq2zaaaBEWZITz",
"use": "sig",
"alg": "RS256",
"n": "qSVxcknOm0uCq5vGsOmaorPDzHUubBmZZ4UXj-9do7w9X1uKFXAnqfto4TepSNuYU2bA_-tzSLAGBsR-BqvT6w9SjxakeiyQpVmexxnDw5WZwpWenUAcYrfSPEoNU-0hAQwFYgqZwJQMN8ptxkd0170PFauwACOx4Hfr-9FPGy8NCoIO4MfLXzJ3mJ7xqgIZp3NIOGXz-GIAbCf13ii7kSStpYqN3L_zzpvXUAos1FJ9IPXRV84tIZpFVh2lmRh0h8ImK-vI42dwlD_hOIzayL1Xno2R0T-d5AwTSdnep7g-Fwu8-sj4cCRWq3bd61Zs2QOJ8iustH0vSRMYdP5oYQ"
}
A JWK anterior está no formato JSON. Para configurar um plug-in de autenticação JWT no formato YAML, use uma JWK no formato YAML.
Em um
plug-in de autenticação JWT, basta configurar achave pública. Mantenha suachave privadasegura. A tabela a seguir lista os algoritmos de assinatura com suporte no plug-in de autenticação JWT.
|
Algoritmo de assinatura |
Configuração |
|
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, o valor da chave é codificado em base64url. Se a assinatura for inválida, verifique se a sua chave está no mesmo formato da chave usada para gerar o token.
2. Configurações
Configure um plug-in de autenticação JWT nos formatos JSON ou YAML, pois ambos compartilham o mesmo esquema. Use a ferramenta yaml to json para converter o formato da configuração do plug-in. O exemplo a seguir apresenta um modelo de configuração do plug-in no formato YAML:
---
parameter: X-Token # The parameter from which the JWT is read. It corresponds to an API parameter.
parameterLocation: header # The location from which the JWT is read. Valid values: query and header. This parameter is optional if Request Mode for the bound API is set to Map (Filter Out Unknown Parameters) or Map (Pass-through Unknown Parameters). This parameter is required if Request Mode for the bound API is set to Pass-through.
preventJtiReplay: false # Controls whether to enable the anti-replay check for jti. Default value: false.
bypassEmptyToken: false # Controls whether to forward requests that do not include tokens to backend services without verification.
ignoreExpirationCheck: false # Controls whether to ignore the verification of the exp setting.
orAppAuth: false # The default value is false. Both the Alibaba Cloud App authentication and JWT authentication are required. If the value is true, the other authentication method is not required if one authentication is passed.
claimParameters: # The conversion of claims to parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
#
# Public key in the JWK
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 and use them together with the jwk field.
# If multiple JWKs are configured, kid is required. If the JWT does not include kid, the consistency check on kid fails.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz # If only one JWK is configured, kid is optional. If the JWT includes kid, API Gateway checks the consistency of kid.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz # If only one JWK is configured, kid is optional. If the JWT includes kid, API Gateway checks the consistency of kid.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v...
O
plug-in de autenticação JWTrecupera os JWTs com base nas definições deparametereparameterLocation. Por exemplo, separameterestiver definido como X-Token eparameterLocationcomo header, o JWT será lido do headerX-Token.Não especifique
parameterLocationse o parâmetro configurado em uma API tiver o mesmo nome do parâmetro definido emparameter. Caso contrário, ocorrerá um erro durante a chamada da API.Para transmitir um token em um header Authorization, como
Authorization bearer {token}, definaparametercomo Authorization eparameterLocationcomo header para garantir a leitura correta das informações do token.Quando
preventJtiReplayé definido como true, o plug-in de autenticação JWT usa o campojtinasclaimspara executar a verificação anti-replay.Se
bypassEmptyTokenfor true e a requisição não contiver um token, o API Gateway ignora a verificação e encaminha a requisição diretamente ao serviço de backend.Com
ignoreExpirationCheckdefinido como true, o API Gateway ignora a verificação da configuraçãoexp. Caso contrário, ele verifica se o token expirou.-
Para encaminhar as
claimsdos tokens aos serviços de backend, configuretokenParametersdefinindo os seguintes parâmetros de encaminhamento:claimName: nome da claim no token.parameterName: nome do parâmetro encaminhado ao serviço de backend.-
location: local do parâmetro encaminhado ao serviço de backend. Valores válidos:header,query,patheformData.Se este parâmetro for definido como
path, o caminho de backend deve conter um parâmetro com o mesmo nome, como/path/{userId}.Se este parâmetro for definido como
formData, o corpo da requisição recebida pelo serviço de backend deve ser do tipoForm.
-
Configure apenas uma chave no campo
jwk. Alternativamente, configure várias chaves no campojwks.Apenas uma chave pode ser configurada sem
kidespecificado.Várias chaves podem ser configuradas com
kidespecificado. Okiddeve ser único.
3. Regras de verificação
Um plug-in de autenticação JWT obtém tokens com base nas configurações de
parametereparameterToken. DefinabypassEmptyTokencomo true caso o API Gateway precise encaminhar requisições aos serviços de backend mesmo quando elas não incluírem tokens.-
Ao configurar múltiplas chaves, siga estes princípios:
Priorize a seleção de uma chave cujo ID corresponda ao valor de
kidno token para assinatura e autenticação.Configure apenas uma chave se
kidnão for especificado. Na ausência de uma chave com ID igual ao valor dekiddo token, use a chave semkiddefinido para assinatura e autenticação.Se todas as chaves configuradas tiverem
kidespecificado, mas o token da requisição não contiverkidou nenhuma chave corresponder aokid, um erroA403JKserá retornado.
Caso o token contenha
iat,nbfeexp, o plug-in de autenticação JWT valida seus formatos de tempo. A unidade de tempo é segundos.Por padrão, o API Gateway verifica a configuração
exp. Para ignorar essa verificação, definaignoreExpirationCheckcomo true.Use
tokenParameterspara extrair os parâmetros necessários dasclaimsde um token. Esses parâmetros são encaminhados aos serviços de backend.
4. Configurar um conjunto de dados de plug-in para plug-ins de autenticação JWT
4,1 Criar um conjunto de dados de plug-in de autenticação JWT
Faça login no console do API Gateway. No painel de navegação à esquerda, escolha Manage APIs > Plug-ins.
Na página Plug-in List, clique em na aba Plug-in Datasets.
Clique em Create Dataset no canto superior direito. Na caixa de diálogo exibida, especifique um nome para o conjunto de dados, selecione JWT_JWK_LIST para o parâmetro Type e clique em Confirm.
-
Clique em no conjunto de dados criado. Na página de detalhes do conjunto de dados, clique em Create Dataset Entry no canto superior direito. Defina Data Value como a JWK com suporte no plug-in de autenticação JWT e Validity Period como o período de validade da sua chave pública.
ImportanteAo configurar múltiplas JWKs, use KIDs diferentes. A ordem dos valores de dados da JWK deve seguir o exemplo abaixo.
kty: RSA e: AQAB use: sig kid: N3h666 alg: RS256 n: qfzaxmlnl...
4,2 Exemplo
---
parameter: X-Token # The parameter from which the JWT is read. It corresponds to a parameter in an API request.
parameterLocation: header # The location from which the JWT is read. Valid values: query and header. This parameter is optional if Request Mode for the bound API is set to Request Parameter Mapping(Filter Unknown Parameters) or Request Parameter Mapping(Passthrough Unknown Parameters). This parameter is required if Request Mode for the bound API is set to Request Parameter Passthrough.
claimParameters: # The claims to be converted into parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
preventJtiReplay: false # Controls whether to enable the anti-replay check for jti. Default value: false.
ignoreExpirationCheck: true # Controls whether to ignore the verification of the exp setting.
jwkListDataSet: cb4f000b6b8244329ac25XXXc8a4f9d6 # The dataset ID.
Se o conjunto de dados não entrar em vigor, envie um ticket para solicitar a atualização da sua instância.
5. Exemplos
5,1 Configurar uma única JWK
---
parameter: X-Token # The parameter from which the JWT is read. It corresponds to a parameter in an API request.
parameterLocation: header # The location from which the JWT is read. Valid values: query and header. This parameter is optional if Request Mode for the bound API is set to Request Parameter Mapping(Filter Unknown Parameters) or Request Parameter Mapping(Passthrough Unknown Parameters). This parameter is required if Request Mode for the bound API is set to Request Parameter Passthrough.
claimParameters: # The claims to be converted into parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
preventJtiReplay: false # Controls whether to enable the anti-replay check for jti. Default value: false.
#
# Public key in the JWK
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 Configurar múltiplas JWKs
---
parameter: Authorization # The parameter from which the token is obtained.
parameterLocation: header # The location from which the token is obtained.
claimParameters: # The claims to be converted into parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
preventJtiReplay: true # Controls whether to enable the anti-replay check for jti. Default value: false.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz # kid must be set to different values for different JWKs.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz # kid must be set to different values for different JWKs.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v...
5,3. Ler um token de campos no cookie de uma requisição
---
parameter: cookie # The parameter from which the JWT is read. It corresponds to a parameter in an API request.
parameterLocation: header # The location from which the JWT is read. Valid values: query and header. This parameter is optional if Request Mode for the bound API is set to Request Parameter Mapping(Filter Unknown Parameters) or Request Parameter Mapping(Passthrough Unknown Parameters). This parameter is required if Request Mode for the bound API is set to Request Parameter Passthrough.
parameterSection: token # For example, the value of the cookie parameter is username=tom ; token=abcsef.
claimParameters: # The claims to be converted into parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
preventJtiReplay: true # Controls whether to enable the anti-replay check for jti. Default value: false.
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz # kid must be set to different values for different JWKs.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v....
- kid: 10fpdhrViq2zaaaBEWZITz # kid must be set to different values for different JWKs.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v...
Em alguns cenários web, os usuários podem querer salvar o token em um campo específico do parâmetro Cookie para garantir maior segurança. O plug-in JWT do API Gateway permite a leitura do token a partir de campos do parâmetro Cookie. Especifique o campo para salvar seu token usando o parâmetro parameterSection. No exemplo a seguir, o API Gateway lê o token do header Cookie.
Cookie: acw_tc=123; token=0QzRCMDBBQUYwRjE1MjYxQzU0QjY4NEM5MTc1NTQ1OUVCOTIzNzA4RDk3MDg5MzlDOTMQTVENDZCRUI1NkYyMEUyO; csrf=073957d8d2823be4f6c0cad23c764558
5,4 Configurar uma lista de bloqueios
Plug-ins de autenticação JWT usam listas de bloqueios para impedir requisições enviadas por usuários adicionados a uma lista de bloqueios, mesmo que tenham obtido um token oficial. O plug-in funciona em conjunto com o recurso de conjunto de dados para rejeitar requisições com base nos parâmetros de claim descriptografados do token. Além disso, o API Gateway permite definir respostas personalizadas para as requisições rejeitadas. O código a seguir fornece um exemplo de como configurar uma lista de bloqueios em um plug-in de autenticação JWT. Observe as definições de parâmetros que começam com block:
---
parameter: Authorization # The parameter from which the token is obtained.
parameterLocation: header # The location from which the token is obtained.
claimParameters: # The claims to be converted into parameters. API Gateway maps JWT claims to backend parameters.
- claimName: aud # The name of the JWT claim, which can be public or private.
parameterName: X-Aud # The name of the backend parameter, to which the JWT claim is mapped.
location: header # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
- claimName: userId # The name of the JWT claim, which can be public or private.
parameterName: userId # The name of the backend parameter, to which the JWT claim is mapped.
location: query # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
blockClaimParameterName: userId # The condition that is used for judgment when the blacklist logic is implemented. A request is blocked if the value of this parameter is contained in the dataset of blockByDataSet.
blockByDataSet: 87 b65008e92541938537b1a4a236eda5 # The blacklist.
blockStatusCode: 403 # The status code of the response that is returned to a rejected request.
blockResponseHeaders: # The header of the response that is returned to a rejected request.
Content-Type: application/xml
blockResponseBody: # The body of the response that is returned to a rejected request.
<Reason>be blocked</Reason>
jwks:
- kid: O9fpdhrViq2zaaaBEWZITz # kid must be set to different values for different JWKs.
kty: RSA
e: AQAB
use: sig
alg: RS256
n: qSVxcknOm0uCq5v....
6. Códigos de erro
|
Status |
Código |
Mensagem |
Descrição |
|
400 |
I400JR |
JWT required |
Erro retornado porque os parâmetros relacionados ao JWT não foram encontrados. |
|
403 |
S403JI |
Claim |
Erro retornado porque nenhuma claim |
|
403 |
S403JU |
Claim |
Erro retornado porque a claim |
|
403 |
A403JT |
Invalid JWT: ${Reason} |
Erro retornado porque o |
|
400 |
I400JD |
JWT Deserialize Failed: |
Erro retornado porque falha ao analisar o |
|
403 |
A403JK |
No matching JWK, |
Erro retornado porque nenhuma |
|
403 |
A403JE |
JWT is expired at |
Erro retornado porque o |
|
400 |
I400JP |
Invalid JWT plugin config: ${JWT} |
Erro retornado porque o |
Se uma mensagem de resposta HTTP incluir um código de resposta inesperado especificado por ErrorCode no header X-Ca-Error-Code, como A403JT ou I400JD, visite o site jwt.io para verificar a validade e o formato do token.
7. Limites
Os metadados de um único plug-in não podem exceder 50 KB de tamanho.
É possível configurar no máximo 16 parâmetros para encaminhamento. Nem o parâmetro
claimNamenem o parâmetroparameterNamepodem exceder 32 caracteres de comprimento. Apenas a seguinte expressão regular tem suporte: [A-Za-z0-9-_].Para JWKs,
algpode ser definido como RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384 ou HS512.