All Products
Search
Document Center

Function Compute:Configure JWT Authentication for HTTP Triggers

Last Updated:Mar 19, 2026

Configure JWT authentication for HTTP triggers in Function Compute. This ensures that only clients with valid JSON Web Tokens (JWTs) can access your HTTP services, enhancing security and preventing unauthorized access and malicious attacks.

Background information

Introduction

Function Compute supports JWT authentication for HTTP triggers. A JSON Web Token (JWT), defined in RFC 7519, is a token-based authentication scheme. User state information is stored in the Token and provided by the client. The function does not store this information, making JWT a serverless-friendly authentication method. Function Compute authenticates HTTP invocation requests using the public JSON Web Key Set (JWKS) bound to the HTTP trigger. Based on the HTTP trigger's configuration, Function Compute forwards the claims as parameters to the function. The function does not need to authenticate requests. It focuses solely on business logic. For more information about the JWT Token authentication process and basic concepts, see Token Authentication Based on JWT and Introduction to JWT.

JWT Authentication Flow

image

The preceding figure shows the sequence diagram of the entire business flow for JWT authentication using Function Compute HTTP triggers with asymmetric encryption. The steps are as follows.

  1. The client sends an authentication request to the custom authorization service. This request typically includes the end user's username and password.

  2. The custom authorization service reads and verifies the authentication information, such as the username and password, from the request. After successful verification, it generates a standard Token using the private key.

  3. The custom authorization service returns a response containing the Token to the client. The client must cache this Token locally.

  4. The client sends a business request to the HTTP trigger, including the Token.

  5. The HTTP trigger verifies the Token in the request using the public key configured by the user.

  6. After successful verification, the request is passed to the protected function.

  7. The protected function processes the business request and returns a response.

  8. The HTTP trigger returns the business response to the client.

Prerequisites

Limits

  • You can generate and distribute JWTs using any method. Function Compute authenticates JWTs using the public JWKS configured on the trigger.

  • JWKS without a kid are supported.

  • You can read the token from header, Query parameters (GET), form parameters (POST), and cookie.

  • You can forward claims to the function as header, form parameters (POST), and cookie.

  • Function Compute supports configuring a set of JSON Web Keys (JWKS) for an HTTP trigger. It searches the JWKS for a public JWK with the same kid as the Token and uses this public key to verify the Token's signature. A trigger's JWKS allows at most one JWK to have a missing or empty kid.

    Function Compute's JWT supports the following algorithms.

    Signature Algorithm

    alg Value

    RSASSA-PKCS1-V1_5

    RS256, RS384, RS512

    RSASSA-PSS

    PS256, PS384, PS512

    Elliptic Curve (ECDSA)

    ES256, ES384, ES512

    HMAC

    HS256, HS384, HS512

    EdDSA

    EdDSA

    Important
    • HMAC signature algorithms use symmetric encryption, which provides lower security. Use asymmetric encryption algorithms for higher security.

    • When using asymmetric encryption algorithms, include only public key information in your JWT. Do not include private key information.

    • Use HTTPS to protect sensitive information, such as the Token, in requests. This prevents Token leakage.

Procedure

Step 1: Configure JWT Authentication

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.

  2. In the top navigation bar, select a region. On the Services page, click the desired service.

  3. On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Trigger Management (URL) tab.

  4. On the Trigger Management (URL) tab, click the Edit button in the Actions column for the HTTP trigger.

  5. On the Edit Trigger panel, configure the following items, then click OK.

    1. Set Authentication Method to JWT Authentication.

      image

    2. Configure JWKS.

      To configure JWT authentication for an HTTP trigger, provide a valid JSON Web Key Set (JWKS). Generate a JWKS yourself, or search for JSON Web Key Generator to find online tools, such as mkjwk.org. If you have a PEM-formatted key, use a tool, such as jwx, to convert it to JWKS format.

      This topic demonstrates generating a JWKS using mkjwk.org. As shown in the following figure, on the generation interface, set Key Use to Signature, Algorithm to RS256, and Show X.509 to Yes. Then, click Generate. Use the Private Key (① in the figure) in your code to issue JWT Tokens. Keep it secure. Copy the content of the Public Key (② in the figure) into the keys array of the JWKS configuration in the console.

      image.png

      image

      The following example shows the JWKS configured in this topic.

      {
          "keys": [
              {
                  "alg": "RS256",
                  "e": "AQAB",
                  "kty": "RSA",
                  "n": "u1LWgoomekdOMfB1lEe96OHehd4XRNCbZRm96RqwOYTTc28Sc_U5wKV2umDzolfoI682ct2BNnRRahYgZPhbOCzHYM6i8sRXjz9Ghx3QHw9zrYACtArwQxrTFiejbfzDPGdPrMQg7T8wjtLtkSyDmCzeXpbIdwmxuLyt_ahLfHelr94kEksMDa42V4Fi5bMW4cCLjlEKzBEHGmFdT8UbLPCvpgsM84JK63e5ifdeI9NdadbC8ZMiR--dFCujT7AgRRyMzxgdn2l-nZJ2ZaYzbLUtAW5_U2kfRVkDNa8d1g__2V5zjU6nfLJ1S2MoXMgRgDPeHpEehZVu2kNaSFvDUQ",
                  "use": "sig"
              }
          ]
      }
    3. In the JWT Token Configuration, select the Token location and Token name.

      Token location supports Header, Cookie, Query parameters (GET), and form parameters (POST). If you select Header as the Token location, specify the Parameter Name and Prefix to Remove. Function Compute removes the prefix content set in Prefix to Remove when retrieving the Token.set_token

      Important

      When setting Prefix to Remove, check for a space after the prefix. Add a space after the prefix field, such as Bearer .

    4. In the JWT Claim Transformation configuration, select the parameter location, original parameter name, and the parameter name after passing it to the function.

      Mapped parameter locations support Header, Cookie, and form parameters (POST).jwt_claim_switch

    5. Set the request matching mode.

      • Match All: All HTTP requests require JWT validation.

      • Whitelist Mode: HTTP requests with paths set in the Request Path Whitelist do not require JWT validation. Other requests require JWT validation.

      • Blacklist Mode: HTTP requests with paths set in the Request Path Blacklist require JWT validation. Other requests do not require JWT validation.

      Whitelist Mode and Blacklist Mode support the following two matching modes.

      • Exact match

        The request path must exactly match the configured path. For example, if you set the Request Path Blacklist to /a, requests from path /a require JWT validation. Requests from path /a/ do not require validation.

      • Fuzzy match

        Use a wildcard character (*) to set paths. The wildcard character (*) can appear only at the end of the path. For example, if you set the Request Path Blacklist to /login/*, requests with the path prefix /login/ (such as /login/a or /login/b/c/d) require JWT validation.

Step 2: Operation Verification

In a debugging tool, such as Postman, enter the access endpoint and Token based on the HTTP trigger's JWT configuration. Verify that you can access the HTTP service.

  1. Use the X.509 PEM-formatted Private Key generated in Step 1 as the private key to issue JWT Tokens. The following steps demonstrate how to generate a Token using a local Python script.

    1. Install the PyJWT module.

      pip install 'PyJWT>=2.0'
    2. Run the following Python example script locally to generate a JWT Token.

      import jwt
      import time
      
      private_key = """
      -----BEGIN PRIVATE KEY-----
      <Use the X.509 PEM-formatted private key generated in Step 1>
      -----END PRIVATE KEY-----
      """
      
      headers = {
          "alg": "RS256",
          "typ": "JWT"
      }
      
      payload = {
          "sub": "1234567890",
          "name": "John Snow",
          "iat": int(time.time()),   # Token issuance time
          "exp": int(time.time()) + 60 * 60,   # Set token validity to 1 hour
      }
      
      
      encoded = jwt.encode(payload=payload, key=private_key.encode(), headers=headers)
      print("Generated token: %s" % encoded)
      
  2. Use Postman to verify that the HTTP service is accessible.

    1. On the Trigger Management (URL) tab of the target function, retrieve the public network access endpoint of the HTTP trigger and enter it in the URL field in Postman.

    2. In Postman's Headers, configure the Token parameter information, then click Send to send the request. The following example shows the Token filled in this topic.

      Name

      Example Value

      Description

      Key

      Authentication

      The parameter name set in JWT Token Configuration.

      Value

      Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9uIFNub3ciLCJhZG1pbiI6dHJ1ZSwiZXhwIjo0ODI5NTk3NjQxfQ.eRcobbpjAd3OSMxcWbmbicOTLjO2vuLR9F2QZMK4rz1JqfSRHgwQVqNxcfOIO9ckDMNlF_3jtdfCfvXfka-phJZpHmnaQJxmnOA8zA3R4wF4GUQdz5zkt74cK9jLAXpokwrviz2ROehwxTCwa0naRd_N9eFhvTRnP3u7L0xn3ll4iOf8Q4jS0mVLpjyTa5WiBkN5xi9hkFxd__p98Pah_Yf0hVQ2ldGSyTtAMmdM1Bvzad-kdZ_wW0jcctIla9bLnOo-Enr14EsGvziMh_QTZ3HQtJuToSKZ11xkNgaz7an5de6PuF5ISXQzxigpFVIkG765aEDVtEnFkMO0xyPGLQ

      In JWT Token Configuration, you can configure the system to remove the prefix when constructing the JWT token. For example, assume the prefix to be removed is set to Bearer .

      Important

      Note that the prefix and space of the JWT parameter in the request header must match the Prefix to Remove content set in JWT Token Configuration. Otherwise, the trigger fails to parse the Token and returns an "invalid or expired jwt" error.

Use JWT Authentication with Custom Domain Names

image

As shown in the preceding figure, the custom domain name is located before the HTTP trigger. User requests are first processed by the custom domain name, then by the HTTP trigger. JWT authentication logic resides on the HTTP trigger. The following describes how to use JWT authentication with custom domain names.

Normal Custom Domain Names

If you configure routing for a custom domain name but do not configure a rewrite policy, the path in the incoming HTTP request is the path of the custom domain name request.

Assume the routing rules for the custom domain name www.fc-jwt.com are as follows. The HTTP trigger for the function jwt-demo has JWT authentication configured with the Request Path Blacklist set to /fc-jwt/auth/*.

Path

Service Name

Function Name

Version

/fc-jwt/*

jwt

jwt-demo

1

If the user requests the URL /fc-jwt/auth/aliyun, the HTTP trigger validates the request because the path reaching the HTTP trigger matches the configured Request Path Blacklist.

Combine with Custom Domain Name Rewrite Feature

If you configure routing for a custom domain name and a rewrite policy, the path in the incoming HTTP request is the rewritten path of the custom domain name. For more information about the custom domain name rewrite feature, see Configure Rewrite Policies (Public Preview).

Assume the routing rules for the custom domain name www.fc-jwt.com are as follows. The HTTP trigger for the function jwt-demo has JWT authentication configured with the Request Path Blacklist set to /fc-jwt/auth/*. A wildcard rewrite policy is also configured (match rule is /fc-jwt/*, replace rule is /$1).

Path

Service Name

Function Name

Version

/fc-jwt/*

jwt

jwt-demo

1

If the user requests the URL /fc-jwt/auth/aliyun, the rewritten URL is /auth/aliyun. For more information about wildcard rewrite rules, see Wildcard Rewrites. In this case, the HTTP trigger does not validate the request because the path reaching the HTTP trigger is /auth/aliyun, which does not match the configured Request Path Blacklist.

If you configure the trigger's Request Path Blacklist as /auth/*, the HTTP trigger performs JWT validation for requests to the URL /fc-jwt/auth/aliyun.

FAQ

Why does accessing the function return "invalid or expired jwt" after enabling JWT authentication for the trigger?

This message indicates JWT authentication failed. Possible reasons include the following:

  • Your Token signature or format is invalid, causing validation errors.

  • Your Token has expired, causing validation errors.

  • The kid in your token does not match the JWKS configured in the trigger, or the matched JWK is inaccurate, which prevents correct token validation.

Why does accessing the function return "the jwt token is missing" after enabling JWT authentication for the trigger?

This message indicates Function Compute cannot find the Token based on the JWT Token configuration. Check whether the request includes the Token and whether the Token's location or name is correct. If you select Header as the read location when configuring JWT Token Configuration, add the Prefix to Remove and a space when setting the Token. Otherwise, an error occurs.

Does enabling JWT authentication incur additional billing?

No additional billing is incurred. Function Compute's default gateway-related features are billed based on function invocation count. Therefore, enabling JWT authentication does not incur extra billing.