All Products
Search
Document Center

API Gateway:Jwt authentication plug-in

Last Updated:Mar 17, 2025

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 distribute JWT by any method. The API Gateway solely handles the authentication of JWT using the public JWK.

  • Supports jwk without a kid.

  • Supports the configuration of multiple jwk instances.

  • Supports directly reading the token from the header or query, 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 as Authorization bearer {token}, configure it with parameter: Authorization and parameterLocation: header to ensure the token is read correctly.

  • By including the preventJtiReplay: true configuration, you enable anti-replay checks that are based on the claim: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 the exp 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 the Public Key. Ensure the Private Key is stored securely. The JWT authentication plug-in currently supports these algorithms:

Signature algorithm

Supported alg values

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

Important

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 specified parameter and parameterLocation to retrieve the JWT value. For instance, parameter: X-Token and parameterLocation: header signify that the JWT is obtained from the request's X-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 with parameter: Authorization and parameterLocation: header. The JWT plug-in will then correctly retrieve the token value.

  • When preventJtiReplay: true is set, the plug-in utilizes the jti field within claims 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 of exp. 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 the tokenParameters 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 include header, query, path, and formData.

      • 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 the parameter mapping is correct and the package body is in form format.

  • You can configure either a single key in the jwk field or multiple keys in the jwks field.

    • You can only configure one key without the kid field.

    • Multiple keys can be configured with the kid attribute, but each kid must be unique.

3. Verification rules

  • The plug-in retrieves the token using the specified parameter and parameterToken. To forward requests to the backend when the token is absent, configure bypassEmptyToken: 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 matching kid, the key without kid should be used for signature verification.

    • If no key without kid is configured, and the request token lacks a kid, or if no key matches the kid, the system will report an A403JK error.

  • If the token includes the iat, nbf, and exp 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 for exp, configure ignoreExpirationCheck: true.

  • If the tokenParameters field is set up for forwarding, then when the claims in the token include the relevant fields, those claim fields will be passed on to the backend. Any claim 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

  1. Log on to the API Gateway console. In the left-side navigation pane, click API Management > Plug-in Management.

  2. On the plug-in list page, select Plug-in Dataset.

  3. 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.

  4. 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.

    Important

    When 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
Note

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 jti is required when preventJtiReplay:true

When the anti-replay feature is configured in the JWT authentication plug-in, the request does not provide a valid jti.

403

S403JU

Claim jti in JWT is used

When the anti-replay feature is configured in the JWT authentication plug-in, the jti provided in the request has been used.

403

A403JT

Invalid JWT: ${Reason}

The JWT provided in the request is invalid.

400

I400JD

JWT Deserialize Failed: ${Token}

The JWT provided in the request failed to parse.

403

A403JK

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

The kid in the request JWT does not match any JWK.

403

A403JE

JWT is expired at ${Date}

The JWT provided in the request is expired.

400

I400JP

Invalid JWT plugin config: ${JWT}

JWT authentication plug-in configuration error.

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 and parameterName 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.