Json Web Token (RFC7519) offers a convenient authentication method that the gateway can use for request authentication. The API Gateway
can conduct JWT authentication on incoming requests by utilizing the user's Public JWK
, and it can forward claims
as backend parameters, streamlining backend application development. This topic primarily discusses how to configure the JWT authentication plug-in. For details on the JWT token authentication process and foundational concepts, see JWT-based token authentication.
The OpenId Connect
feature originally configured on the API can now be implemented using the JWT authentication plug-in
. It is advisable to configure the JWT authentication
plug-in. The JWT authentication
plug-in offers several advantages over the API's OpenId Connect
authentication:
There's no need to set up an additional
authorization API
. You can generate and distributeJWT
by any method. The API Gateway solely handles the authentication ofJWT
using thepublic JWK
.Supports
jwk
without akid
.Supports the configuration of multiple
jwk
instances.Supports directly reading the token from the
header
orquery
, eliminating the need to set the token parameter for each API.Support for reading the token from fields in the request cookie header.
When the
JWT
is transmitted asAuthorization bearer {token}
, configure it withparameter: Authorization
andparameterLocation: header
to ensure the token is read correctly.By including the
preventJtiReplay: true
configuration, you enable anti-replay checks that are based on theclaim:jti
.By setting the
bypassEmptyToken: true
configuration, you can bypass verification and directly forward requests to the backend when the token is absent.By including the
ignoreExpirationCheck: true
configuration, you can bypass the token's expiration check specified by theexp
field.
When you configure the JWT authentication plug-in
and associate it with an API that already has the OpenId Connect
feature, the existing OpenId Connect
configuration on the API
will be superseded by the plug-in's settings.
1. Obtain a JWK (JSON web key)
The JWT authentication plug-in utilizes JSON Web Key (JWK) as defined in RFC7517 for token signing and authentication. To set up the JWT authentication plug-in
, you must first generate a valid JSON Web Key
. This can be done manually or by using an online tool such as JSON Web Key Generator
. For assistance, you can visit websites like mkjwk.org. A typical JSON Web Key
includes a private key for token signing and a public key that must be configured in the JWT authentication
plug-in. A standard JWK format is as follows:
{
"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 JSON format is shown here. When using the YAML format to configure the plug-in, conversion is required.*
The
JWT authentication plug-in
requires only the configuration of thePublic Key
. Ensure thePrivate Key
is stored securely. The JWT authentication plug-in currently supports these algorithms:
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 configuring keys of type HS256, HS384, or HS512, the key must be a Base64 UrlEncoded value. If you encounter an Invalid Signature issue, please check whether the format of your key is consistent with the key used to generate the token.
2. Configurations
You can configure your plug-in using either JSON or YAML format, as both share the same schema. To convert between formats, look for yaml to json
conversion tools. Below is a table displaying the YAML format template.
---
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 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.
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
utilizes the specifiedparameter
andparameterLocation
to retrieve the JWT value. For instance,parameter: X-Token
andparameterLocation: header
signify that the JWT is obtained from the request'sX-Token
header.If the API is configured with a
parameter
that shares its name,parameterLocation
may be omitted. If not, an error will occur upon invocation.When transmitting the token via the Authorization header, for example,
Authorization bearer {token}
, configure it withparameter: Authorization
andparameterLocation: header
. The JWT plug-in will then correctly retrieve the token value.When
preventJtiReplay: true
is set, the plug-in utilizes thejti
field withinclaims
to perform anti-replay checks.When
bypassEmptyToken: true
is set, requests with empty token parameters can bypass checks and be directly routed to the backend.When
ignoreExpirationCheck: true
is set, the system will bypass the expiration check ofexp
. If not configured, the gateway will verify if the token is expired.To have the API Gateway forward the
claims
from the token to the backend application, configure the forwarding parameters using thetokenParameters
field.claimName
: This refers to the name of the claim within the token.parameterName
: This is the name of the parameter forwarded to the backend.location
: Specifies where the parameter is forwarded to the backend. Possible values includeheader
,query
,path
, andformData
.When set to
path
, the backend path must include a parameter of the same name, for instance,/path/{userId}
.When set to
formData
, it supports accurate mapping to the backend form only if theparameter mapping
is correct and the package body is inform
format.
You can configure either a single key in the
jwk
field or multiple keys in thejwks
field.You can only configure one key without the
kid
field.Multiple keys can be configured with the
kid
attribute, but eachkid
must be unique.
3. Verification rules
The plug-in retrieves the token using the specified
parameter
andparameterToken
. To forward requests to the backend when the token is absent, configurebypassEmptyToken: true
.The selection principle for configuring multiple keys is as follows:
Prefer selecting the key that corresponds to the
kid
in the request token to verify the signature.Keys lacking a
kid
attribute can only be set up singularly. If the request token does not contain a matchingkid
, the key withoutkid
should be used for signature verification.If no key without
kid
is configured, and the request token lacks akid
, or if no key matches thekid
, the system will report anA403JK
error.
If the token includes the
iat
,nbf
, andexp
fields, the JWT plug-in will check the time fields for validity. The time is measured in seconds (s).By default, the API Gateway verifies the
exp
field, which represents the token's expiration time. To bypass the expiration check forexp
, configureignoreExpirationCheck: true
.If the
tokenParameters
field is set up for forwarding, then when theclaims
in the token include the relevant fields, thoseclaim
fields will be passed on to the backend. Anyclaim
fields that do not exist will not be forwarded.
4. Configure a plug-in dataset for JWT authentication plug-ins
4.1 Create a JWT authentication plug-in dataset
Log on to the API Gateway console. In the left-side navigation pane, click .
On the plug-in list page, select Plug-in Dataset.
Click Create Dataset in the upper-right corner. In the pop-up box, customize the Name of the dataset, select JWT_JWK_LIST for Type, and click OK to generate the dataset.
Enter the newly generated dataset, click Create Dataset Entry in the upper-right corner, configure the JWK supported by the JWT authentication plug-in in Data Value, and configure the validity period of the public key in Expiration Time.
ImportantWhen configuring multiple JWKs, you need to use different kids. The order of JWK data values must be configured according to the following example.
kty: RSA e: AQAB use: sig kid: N3h666 alg: RS256 n: qfzaxmlnl...
4.2 Example of configuring a plug-in dataset for JWT authentication plug-ins
---
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 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 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.
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 # Plug-in dataset ID
If the dataset does not take effect, submit a ticket to have your instance upgraded.
5. Examples
5.1 Configure a single JWK
---
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 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 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.
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 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 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.
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 Read a token from fields in the cookie of a request
---
parameter: cookie # 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 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 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.
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, for security reasons, users may want to store the token in a specified field of the cookie. The API Gateway's JWT plug-in supports reading the token from fields in the request cookie. You can specify the field name using the parameterSection parameter feature. For example, if the request cookie header is as follows, the API Gateway can extract the token from the cookie.
Cookie: acw_tc=123; token=0QzRCMDBBQUYwRjE1MjYxQzU0QjY4NEM5MTc1NTQ1OUVCOTIzNzA4RDk3MDg5MzlDOTMQTVENDZCRUI1NkYyMEUyO; csrf=073957d8d2823be4f6c0cad23c764558
5.4 Configure a blacklist
The use case for a JWT authentication plug-in blacklist is to block requests from users who have obtained an official token but have been added to a blacklist. The JWT authentication plug-in of the API Gateway enables the ability to reject requests based on claim parameters decrypted from the token by combining the plug-in dataset feature for this scenario. Additionally, API Gateway allows you to set custom responses to the rejected requests. The following code provides an example of how to configure 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 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.
blockClaimParameterName: userId # The parameter used as a condition when executing blacklist logic. If the value of this parameter is in the blockByDataSet dataset, it will be blocked.
blockByDataSet: 87b65008e92541938537b1a4a236eda5 # Blacklist dataset
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. Error codes
Status | Code | Message | Description |
400 | I400JR | JWT required | JWT parameter not found. |
403 | S403JI | Claim | When the anti-replay feature is configured in the |
403 | S403JU | Claim | When the anti-replay feature is configured in the |
403 | A403JT | Invalid JWT: ${Reason} | The |
400 | I400JD | JWT Deserialize Failed: | The |
403 | A403JK | No matching JWK, | The |
403 | A403JE | JWT is expired at | The |
400 | I400JP | Invalid JWT plugin config: ${JWT} |
|
When an unexpected response code occurs, check the HTTP response for the X-Ca-Error-Code
header to obtain the ErrorCode
, and the X-Ca-Error-Message
header to obtain the ErrorMessage
. When the error code A403JT
or I400JD
occurs, you can visit the jwt.io website to check the validity and format of your token.
7. Limits
The size limit for plug-in metadata is 50KB.
The forwarding parameter list has a maximum limit of 16 items. The
claimName
andparameterName
must not exceed 32 characters in length. Only characters from the set [A-Za-z0-9-_] are supported.The list of supported algorithms (
alg
) for JWK includes: RS256, RS384, RS512, ES256, ES384, ES512, HS256, HS384, and HS512.