Help Center/ API Gateway/ Best Practices/ API Policies/ Using the JWT Authentication Policy to Implement Identity Authentication and Key Rotation0
Updated on 2025-10-31 GMT+08:00

Using the JWT Authentication Policy to Implement Identity Authentication and Key Rotation0

Scenario

JSON Web Token (JWT) is a lightweight token based on JSON. It uses digital signatures to securely transmit information and is widely used for authentication and data exchange.

In typical usage, when a user logs in, the authentication server generates a JWT. The client then includes this token in subsequent requests to access protected resources. The gateway validates the token (signature, expiration, etc.) and extracts user identity and permissions from the payload.

JWT security depends on the signature key. Key rotation (periodically or as required) is a key practice to ensure JWT security. Using the same key for a long period increases the risk of leakage, whether through malicious theft or internal misuse. Regular rotation reduces this risk, and in the event of a suspected leak, emergency rotation can immediately invalidate the old key, preventing attackers from forging tokens.

Advantages

The JWT authentication policy supports token setting in the header, query, and cookie and validates them for identity verification. It can read claim from the payload to extract user information and pass it to backend services. By configuring a JWKS_URI, the gateway can fetch updated public keys for seamless key rotation.

Notes and Constraints

  • The token carried in the request must comply with RFC 7519. The public key configured in the JWT authentication policy must be a JSON string that complies with RFC 7517.
  • JWT does not encrypt data. Do not set sensitive data in tokens. To prevent token leakage, you are advised not to use JWT authentication for APIs whose request protocol is HTTP.
  • APIG verifies the nbf (time when the token takes effect) and exp (token expiration time) fields in the token. If the verification fails, the request is rejected.
  • Token verification supports the following encryption algorithms: RS256, RS384, RS512, ES256, ES384, and ES512. When the RSA algorithm is used, it is recommended that the key length be greater than or equal to 3,072 bits.
  • If the public key is set to be periodically pulled, ensure that JWKS_URI and the APIG gateway can communicate with each other. The scheduled task in APIG requests JWKS_URI every 5 minutes. The returned response body is used as the public key, and the result of the current request overwrites the result of the previous request. If you want to rotate the public and private keys, you are advised to reserve a grace period each time when the keys are rotated. In this way, JWKS_URI returns the new public key and the old public key that is replaced during the rotation, so that the tokens issued by the new and old private keys are valid in this period.
  • The gateway matches and verifies the signature based on the kid in the token and the JWKS public key. If the JWKS contains only one JWK, the kid can be empty. Otherwise, the kid cannot be empty. The kid of any two JWKs in the JWKS must be different. If kid is not set, the token issued before the public and private keys are replaced cannot be verified.
  • For more restrictions, see JWT Authentication .

General Procedure

  1. Generating a key pair and issuing a token

    Generate a key pair and issue a token online or locally.

  2. Setting up the JWKS service address

    Create and maintain an online service for the gateway to access and obtain the JWK public key.

  3. Creating a JWT authentication policy

    Configure a JWT authentication policy and set JWKS_URI.

  4. Binding the policy to an API

    Bind the JWT authentication policy to the API.

  5. Checking whether the JWT authentication takes effect

    Change the token carried in the request to check whether the API is protected by the JWT authentication policy.

  6. Implementing key rotation

    Replace the public key returned by the remote JWKS service to implement key rotation.

  7. Checking whether the key rotation takes effect

    Check whether the token issued using the new private key can be authenticated.

Procedure for Using JWT Authentication Policies to Implement Identity Authentication and Key Rotation

  1. Generate a key pair and issue a token.

    JWT issuing and verification depend on a key pair. You can generate a key pair online or locally and use the private key to issue a token. Keep the private key secure.
    • Online generation
      1. Log in to the JWK key generation platform, set Key Size to 3072, Algorithm to RS256, and Show X.509 to Yes, enter a custom key ID, and click Generate. The JWK and the corresponding key in X.509 format are generated.

      2. Log in to the JWT generation platform, set Algorithm to RS256, add the kid (key ID) field defined in the previous step to the JSON structure corresponding to the header, and enter the public and private keys generated in the previous step. The JWT is automatically generated in the left box.

    • Local generation

      You can use the open-source JWT code repository to run code locally to generate key pairs and issue tokens. The following is a Python code example for generating key pairs and issuing tokens.

      import jwt
      from cryptography.hazmat.primitives.asymmetric import rsa
      from cryptography.hazmat.primitives import serialization
      from jwcrypto.jwk import JWK
      import datetime
      private_key = rsa.generate_private_key(
          public_exponent=65537,
          key_size=3072
      )
      pem_private = private_key.private_bytes(
          encoding=serialization.Encoding.PEM,
          format=serialization.PrivateFormat.PKCS8,
          encryption_algorithm=serialization.NoEncryption()
      )
      public_key = private_key.public_key()
      pem_public = public_key.public_bytes(
          encoding=serialization.Encoding.PEM,
          format=serialization.PublicFormat.SubjectPublicKeyInfo
      )
      jwk_public = JWK.from_pem(pem_public)
      jwk_public_dict = jwk_public.export(as_dict=True)
      test_kid = "test"
      jwk_public_dict['kid'] = test_kid
      payload = {
          "sub": "1234567890",
          "name": "John Doe",
          "iat": datetime.datetime.utcnow(),
      }
      token = jwt.encode(
          payload,
          pem_private,
          algorithm="RS256",
          headers={"kid": test_kid}
      )
      print("======= Public Key (JWK Format) =======")
      print(jwk_public_dict)
      print("\n======= Private Key (PEM Format) =======")
      print(pem_private.decode('utf-8'))
      print("\n======= JWT =======")
      print(token)

  2. Set up the JWKS service address.

    Set up and maintain an online service that returns public keys based on the key pair generated in 1. APIG accesses this service every 5 minutes to obtain and cache the public key. In addition, key rotation requires multiple public and private key pairs with different key IDs.

    The following is a Python code example of the remote service that returns two JWK public keys:

    from flask import Flask, request, abort, Response, jsonify, url_for
    import json
    import time
    app = Flask(__name__)
    @app.route("/jwks", methods=["GET"])
    def echo():
        return jsonify({
            "keys": [
                {
                    "kty": "RSA",
                    "e": "AQAB",
                    "kid": "test-kid-1",
                    "alg": "RS384",
                    "n": "oZaD8Tu7VKC1hnOvCa-DiouYKdHGaioKIWIu-vfvM0JHJdfFLOxJ4BVTksySZcWdv854_81hrYVpyIz_YjC8YHfQHmbtOjRQjcYHzQqoZTiZnS-NRjk4tjzYfOsc1F3oijZutxyeZctCgTn-gUyXIhXzKHsum-G4I0xWbBZzCGE7l0lMBHi6snrhwDz9eHwUSZviOYpKoYBf88FtBhHJTIt2_VLIrXRvwwP_joEMT56vKvX0dTpKE4HHMENWT4-p8IVyCJvtfPdZEg8hAgqfT4O0DHvfOpxAkSkVJpvJs3MA-VbYYRmZufM8TDI9jIyMffKIxxJEbzLgpBp-oy41mbOI-VSJpYnaBRRz1XV0GLeUIz_ri9Or8M29fGQb_hO1o5dLC5X06OzRZ--VENf53mnXwdUwesROexMF4_5JCJ7-Pefi0b6DTIQiPYd0IvKajzN1jwP4WfDzZE5E5FsX84gbkBn2G3aLgU2EPPoX7LPZTdlWMr5jF4FjT73HF0cr",
                },
                {
                    "kty": "RSA",
                    "e": "AQAB",
                    "kid": "test-kid-2",
                    "alg": "RS256",
                    "n": "lRv_mMn0hRIAlMjrcGnyFTIasr7rqwdK2GrQ5rNF76ZGrl-NVGpVTRq0IzcYzyOmLiFGfu1E-Tgs4aPwMyOVy1rXlXIlKYOShGblEIrtsFgd6b-xr09WKZcYTnnV16wH68WjpELDfFUNJ48GNU-c7co2UroQhUZ4Rh8dHIHl89-bayYMwBFMmVfVcimgF4xPut0weJdDm-bdU3RR1qJfjimnAyEA37qYynl7YTVGRBGM4kLnWn3sSJMDDd8v8AJMTHhWyi_DS5K7azkbQQMDd5hPKn_ylJ_-700N5fUqIWELSlj1L85qPdpQ62j109ShcFpVAXKvg64qGesxlLdzbgV6D3NWN_7wuGZS-exEi-gVJgMo-V1pNTMacRuooAK-VX6N-ds9nSMXb8P825XcFvGT1NecI5E7VcmqEvHjKcTEuGVWlTqLUjfM9szOC4wAHMfmFCXhiEAkfwq6kK39uM6hwKkUm_-HYUL_YbOWNRJ-hOtc7ooNMy4EXgDhLgK1"
                }
            ]
        }), 200
    if __name__ == '__main__':
        app.run(port=8080)

  3. Create a JWT authentication policy.

    1. Log in to the APIG console and create a JWT authentication policy.
    2. In the navigation pane, choose API Management > API Policies. Click Create Policy, and select JWT Authentication.
    3. Set Retrieval Mode to Scheduled, and enter the URL of the JWKS service in JWKS_URI. Retain the default values for other parameters. Ensure that the APIG gateway can communicate with the JWKS service address.
    4. Click OK.

  4. Bind this policy to an API.

    1. Click the policy name to go to the policy details page.
    2. Click Select APIs, select the API group, environment, and the API to be bound, and click OK.

  5. Check whether the JWT authentication takes effect.

    Call the API with the bound JWT policy. If the request carries a token generated with the specified private key, it passes the JWT authentication and accesses the backend. Otherwise, authentication fails.

  6. Implement key rotation.

    During each key rotation, the JWKS service will return the new public key, and requests must use tokens signed with the new private key to access APIs. To avoid immediate failure of tokens signed by the old key, configure the JWKS service to return both the old and new public keys during a grace period (based on the expiration time of the old keys).

    For example, if the kid of the old key is test-kid-1, then during rotation the JWKS service should return both the old key (test-kid-1) and the new key (test-kid-2). This allows tokens signed by either key to pass JWT authentication until old tokens expire, after which only the new key (test-kid-2) should be returned.

  7. Check whether the verification key rotation takes effect.

    Call the API bound with the JWT authentication policy based on 6. After rotation, requests with tokens signed by the new key should pass the authentication. During the grace period, tokens signed by either the old or new key should both be accepted.