RFC 7519-compliant JSON Web Token (JWT) is a convenient method used by API Gateway to authenticate requests. API Gateway
hosts the public JSON Web Keys (JWKs)
of users and uses these JWKs to sign and authenticate the JWTs in requests. Then, API Gateway forwards claim
parameters to backend services as backend parameters. This simplifies the development of backend applications. This topic describes how to configure a JWT authentication plug-in. For more information about JWT and the authentication process, see JWT-based authentication.
JWT authentication plug-ins
provide the same functions as OpenID Connect
and bring the following benefits:
You do not need to configure an additional
authorization API operation
.JWTs
can be generated and distributed in multiple ways. API Gateway is responsible only forJWT
authentication by usingpublic JWKs
.JWKs
withoutkid
specified are supported.Multiple
JWKs
can be configured.You can read token information from the
header
orquery
parameter of a request.The token can also be read from the Cookie header in a request by using a JWT authentication plug-in.
If you want to transmit a
JWT
in an Authorization header, such asAuthorization bearer {token}
, you can setparameter
to Authorization andparameterLocation
to header, so the token information can be correctly read.The
jti
claim-based anti-replay check is supported if you setpreventJtiReplay
to true.Requests that do not include tokens can be forwarded to backend services without verification if you set
bypassEmptyToken
to true.The verification on the
exp
setting for tokens can be skipped if you setignoreExpirationCheck
to true.
If you configure a JWT authentication plug-in
and bind it to an API
for which the OpenID Connect
feature is configured, the JWT authentication plug-in takes effect in place of the OpenID Connect
feature.
1. Obtain a JWK
RFC 7517-compliant JWKs are used to sign and authenticate JWTs. If you want to configure a JWT authentication plug-in, you must generate a valid JWK
manually or by using an online JWK generator
such as mkjwk.org. The following example shows a valid JWK
. In the JWK example, the private key is used to sign the token, and the public key is configured in the JWT authentication plug-in to authenticate the signature.
{
"kty": "RSA",
"e": "AQAB",
"kid": "O9fpdhrViq2zaaaBEWZITz",
"use": "sig",
"alg": "RS256",
"n": "qSVxcknOm0uCq5vGsOmaorPDzHUubBmZZ4UXj-9do7w9X1uKFXAnqfto4TepSNuYU2bA_-tzSLAGBsR-BqvT6w9SjxakeiyQpVmexxnDw5WZwpWenUAcYrfSPEoNU-0hAQwFYgqZwJQMN8ptxkd0170PFauwACOx4Hfr-9FPGy8NCoIO4MfLXzJ3mJ7xqgIZp3NIOGXz-GIAbCf13ii7kSStpYqN3L_zzpvXUAos1FJ9IPXRV84tIZpFVh2lmRh0h8ImK-vI42dwlD_hOIzayL1Xno2R0T-d5AwTSdnep7g-Fwu8-sj4cCRWq3bd61Zs2QOJ8iustH0vSRMYdP5oYQ"
}
The preceding JWK is in the JSON format. If you want to configure a JWT authentication plug-in in the YAML format, you must use a JWK in the YAML format.*
For a
JWT authentication plug-in
, you need only to configure apublic key
. Keep yourprivate key
safe. The following table lists the signature algorithms supported by the JWT authentication plug-in.
Signature algorithm | Supported |
RSASSA-PKCS1-V1_5 with SHA-2 | RS256, RS384, RS512 |
Elliptic Curve (ECDSA) with SHA-2 | ES256, ES384, ES512 |
HMAC using SHA-2 | HS256, HS384, HS512 |
When you configure a key of the HS256, HS384, or HS512 type, the key value is base64url encoded. If the signature is invalid, check whether your key is in the same format as the key used to generate the token.
2. Configure the plug-in
You can configure a JWT authentication plug-in in the JSON or YAML format because these two formats have the same schema. You can use the yaml to json
tool to convert the plug-in configuration format. The following example shows a plug-in configuration template in the YAML format:
---
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...
The
JWT authentication plug-in
retrieves JWTs based on the settings ofparameter
andparameterLocation
. For example, ifparameter
is set to X-Token andparameterLocation
is set to header, the JWT is read from theX-Token
header.If the parameter configured in an API has the same name as the parameter specified by
parameter
, do not specifyparameterLocation
. Otherwise, an error is reported when the API is called.If you want to transmit a token in an Authorization header, such as
Authorization bearer {token}
, you can setparameter
to Authorization andparameterLocation
to header, so the token information can be correctly read.If
preventJtiReplay
is set to true, the JWT authentication plug-in usesjti
inclaims
to perform an anti-replay check.If
bypassEmptyToken
is set to true and a token is not included in a request, API Gateway skips the check and directly forwards the request to a backend service.If
ignoreExpirationCheck
is set to true, API Gateway skips the verification of theexp
setting. Otherwise, API Gateway checks whether a token expires.If API Gateway is required to forward
claims
in tokens to backend services, you can settokenParameters
to configure the following parameters to be forwarded:claimName
: the name of the claim in a token. When you configure a key of the HS256, HS384, or HS512 type, the key value is base64url encoded. If the signature is invalid, check whether your key is in the same format as the key used to generate the token.kid
configurations are supported.parameterName
: the name of the parameter forwarded to a backend service.location
: the location of the parameter forwarded to a backend service. Valid values:header
,query
,path
, andformData
.If this parameter is set to
path
, the backend path must contain a parameter with the same name, such as/path/{userId}
.If this parameter is set to
formData
, the body of a received request in a backend service must be of theForm
type.
You can configure only one key in the
jwk
field. You can also configure multiple keys in thejwks
field.You can configure only one key with
kid
not specified.You can configure multiple keys with
kid
specified.kid
must be unique.
3. Verification rules
A JWT authentication plug-in obtains tokens based on the settings of
parameter
andparameterToken
. If API Gateway is required to forward requests to backend services even when tokens are not included in the requests, setbypassEmptyToken
to true.If you want to configure multiple keys, abide by the following principles:
Preferentially select a key whose ID is the same as the value of
kid
in a token for signature and authentication.You can configure only one key if
kid
is not specified. If no key whose ID is the same as the value ofkid
in a token exists, use the key that does not have a specifiedkid
for signature and authentication.If all the configured keys have specified
kid
settings, and the token in a request does not containkid
or no keys matchkid
, anA403JK
error is reported.
If a token contains
iat
,nbf
, andexp
, the JWT authentication plug-in verifies the validity of their time formats. The unit of time is seconds.By default, API Gateway verifies the setting of
exp
. If you want to skip the verification, setignoreExpirationCheck
to true.tokenParameters
is configured to extract the required parameters from theclaims
of a token. These parameters are forwarded to backend services.
4. Configuration examples
4.1. Configure a single 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 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.
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
4.2. Configure multiple 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...
4.3. Read a token from fields in the cookie of a request.
---
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 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.
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...
In some web scenarios, users may want to save the token in a specified field of the Cookie parameter to ensure security. The JWT plug-in of API Gateway allows the token to be read from fields of the Cookie parameter. You can specify the field to save your token by using the parameterSection parameter. In the following example, API Gateway can read the token from the Cookie header.
Cookie: acw_tc=123; token=0QzRCMDBBQUYwRjE1MjYxQzU0QjY4NEM5MTc1NTQ1OUVCOTIzNzA4RDk3MDg5MzlDOTMQTVENDZCRUI1NkYyMEUyO; csrf=073957d8d2823be4f6c0cad23c764558
4.4. Configure a blacklist
JWT authentication plug-ins use blacklists to block requests sent from users who have been added to a blacklist but have obtained an official token. The plug-in works with the dataset feature to reject requests based on the claim parameters that are decrypted from the token. In addition, API Gateway allows you to set custom responses to the rejected requests. The following code provides an example about how to configure a blacklist in a JWT authentication plug-in. Note the parameter definitions that start with 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 location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
blockByDataSet: 87 b65008e92541938537b1a4a236eda5 # The location of the backend parameter, to which the JWT claim is mapped. Valid values: query, header, path, and formData.
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....
5. Error codes
Status | Code | Message | Description |
400 | I400JR | JWT required | The error message returned because JWT-related parameters are not found. |
403 | S403JI | Claim | The error message returned because no valid |
403 | S403JU | Claim | The error message returned because the |
403 | A403JT | Invalid JWT: ${Reason} | The error message returned because the |
400 | I400JD | JWT Deserialize Failed: | The error message returned because the |
403 | A403JK | No matching JWK, | The error message returned because no |
403 | A403JE | JWT is expired at | The error message returned because the |
400 | I400JP | Invalid JWT plugin config: ${JWT} | The error message returned because the |
If an HTTP response message includes an unexpected response code specified by ErrorCode in the X-Ca-Error-Code
header, such as A403JT or I400JD
, you can visit the jwt.io website to check the token validity and format.
6. Limits
The metadata of a single plug-in cannot exceed 50 KB in size.
You can configure a maximum of 16 parameters to be forwarded. Both the
claimName
andparameterName
parameters cannot exceed 32 characters in length. Only the following regular expression is supported: [A-Za-z0-9-_].alg
can be set to RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384, or HS512 for JWKs.