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
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.
The client sends an authentication request to the custom authorization service. This request typically includes the end user's username and password.
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
Tokenusing the private key.The custom authorization service returns a response containing the
Tokento the client. The client must cache thisTokenlocally.The client sends a business request to the HTTP trigger, including the
Token.The HTTP trigger verifies the
Tokenin the request using the public key configured by the user.After successful verification, the request is passed to the protected function.
The protected function processes the business request and returns a response.
The HTTP trigger returns the business response to the client.
Prerequisites
The service has been created. For more information, see Creating a Service.
You have created an HTTP function. For specific operations, see Create a function.
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
kidare supported.You can read the token from
header,Queryparameters (GET), form parameters (POST), andcookie.You can forward
claimsto the function asheader, form parameters (POST), andcookie.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
kidas theTokenand uses this public key to verify theToken's signature. A trigger's JWKS allows at most one JWK to have a missing or emptykid.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
ImportantHMAC 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
Tokenleakage.
Procedure
Step 1: Configure JWT Authentication
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the desired service.
On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Trigger Management (URL) tab.
On the Trigger Management (URL) tab, click the Edit button in the Actions column for the HTTP trigger.
On the Edit Trigger panel, configure the following items, then click OK.
Set Authentication Method to JWT Authentication.

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.


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" } ] }In the JWT Token Configuration, select the
Tokenlocation andTokenname.Tokenlocation supports Header, Cookie, Query parameters (GET), and form parameters (POST). If you select Header as theTokenlocation, specify the Parameter Name and Prefix to Remove. Function Compute removes the prefix content set in Prefix to Remove when retrieving the Token.
ImportantWhen setting Prefix to Remove, check for a space after the prefix. Add a space after the prefix field, such as
Bearer.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).

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.
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.
Install the PyJWT module.
pip install 'PyJWT>=2.0'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)
Use Postman to verify that the HTTP service is accessible.
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.
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
AuthenticationThe parameter name set in JWT Token Configuration.
Value
Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9uIFNub3ciLCJhZG1pbiI6dHJ1ZSwiZXhwIjo0ODI5NTk3NjQxfQ.eRcobbpjAd3OSMxcWbmbicOTLjO2vuLR9F2QZMK4rz1JqfSRHgwQVqNxcfOIO9ckDMNlF_3jtdfCfvXfka-phJZpHmnaQJxmnOA8zA3R4wF4GUQdz5zkt74cK9jLAXpokwrviz2ROehwxTCwa0naRd_N9eFhvTRnP3u7L0xn3ll4iOf8Q4jS0mVLpjyTa5WiBkN5xi9hkFxd__p98Pah_Yf0hVQ2ldGSyTtAMmdM1Bvzad-kdZ_wW0jcctIla9bLnOo-Enr14EsGvziMh_QTZ3HQtJuToSKZ11xkNgaz7an5de6PuF5ISXQzxigpFVIkG765aEDVtEnFkMO0xyPGLQIn 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.ImportantNote 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
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.