Configure JSON Web Token (JWT) authentication for an HTTP trigger to ensure only clients with a valid JWT can access your function. This approach secures your HTTP service against unauthorized access and malicious attacks.
Background
Overview
Function Compute supports JWT authentication for HTTP triggers. JWT (JSON Web Token, RFC7519) is a convenient, token-based authentication scheme. User state information is stored in the Token, which is provided by the client. The function (server) does not need to store this information, making it a Serverless-friendly authentication method. Function Compute can authenticate JWTs in HTTP requests by using the public JWKS that you bind to the HTTP trigger. Based on the HTTP trigger configuration, the claims can be forwarded to the function as parameters. This allows the function to focus on business logic instead of performing authentication. To learn more about the JWT Token authentication process and basic concepts, see JWT-based token authentication and Introduction to JWT.
JWT authentication flow
The preceding diagram illustrates the JWT authentication process for an HTTP trigger that uses an asymmetric encryption algorithm:
The client sends an authentication request to a custom authentication service. The request typically includes the end user's username and password.
The custom authentication service verifies the credentials in the request, such as the username and password. After successful verification, it uses a private key to generate a standard token.
The custom authentication service returns the token to the client in a response. The client caches this
tokenlocally.The client sends a business request that includes the token to the HTTP trigger.
The HTTP trigger uses the configured public key to verify the token in the request.
After successful verification, the trigger passes the request 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
A function and an HTTP trigger have been created. For more information, see Create a function and Create a trigger.
Limitations
You can generate and distribute JWTs in any way. Function Compute authenticates JWTs using the public JWKS configured for the trigger.
Function Compute supports JWKs without a key ID (
kid).The trigger can read a token from a
header, aQueryparameter (GET), a form parameter (POST), or acookie.You can forward
claimsto a function as aheader, form parameters (POST), or acookie.Function Compute allows you to configure a JWKS for an HTTP trigger. The system searches the JWKS for a public JWK with a key ID (
kid) that matches thekidin thetoken. The trigger then uses this key to verify the token's signature. A trigger's JWKS can contain at most one JWK that has nokidor has an empty string as thekid.Function Compute 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
ImportantThe HMAC signature algorithm uses symmetric encryption and is less secure. We recommend using more secure asymmetric encryption algorithms.
When you use an asymmetric encryption algorithm, ensure your JWKS contains only public key information for security. Do not include private key details.
We recommend using HTTPS to protect sensitive information in requests, such as the
token.
Procedure
Step 1: Configure JWT authentication
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Trigger tab. Find the HTTP trigger and click Modify in the Modify column.
In the Modify Trigger panel, configure the following parameters and click OK.
For Authentication Method, select JWT Authentication.
Configure JWKS.
To configure JWT authentication for the HTTP trigger, provide a valid JWKS. You can generate your own JWKS or use an online tool by searching for JSON Web Key Generator. For example, you can use mkjwk.org. If you have a key in PEM format, you can use a tool such as jwx to convert it to JWKS format.
This topic uses mkjwk.org to demonstrate how to generate a JWKS. As shown in the following figure, on the key generation page, set Key Use to Signature, Algorithm to RS256, and Show X.509 to Yes, and then click Generate. Use the Private Key (① in the figure) in your code to issue a JWT token and store it securely. Copy the Public Key (② in the figure) and paste it into the keys array of the JWKS configuration in the console.


The following example shows a JWKS configuration:
{ "keys": [ { "alg": "RS256", "e": "AQAB", "kty": "RSA", "n": "u1LWgoomekdOMfB1lEe96OHehd4XRNCbZRm96RqwOYTTc28Sc_U5wKV2umDzolfoI682ct2BNnRRahYgZPhbOCzHYM6i8sRXjz9Ghx3QHw9zrYACtArwQxrTFiejbfzDPGdPrMQg7T8wjtLtkSyDmCzeXpbIdwmxuLyt_ahLfHelr94kEksMDa42V4Fi5bMW4cCLjlEKzBEHGmFdT8UbLPCvpgsM84JK63e5ifdeI9NdadbC8ZMiR--dFCujT7AgRRyMzxgdn2l-nZJ2ZaYzbLUtAW5_U2kfRVkDNa8d1g__2V5zjU6nfLJ1S2MoXMgRgDPeHpEehZVu2kNaSFvDUQ", "use": "sig" } ] }In the JWT Token Configuration section, select the location of the
tokenand specify the name of thetoken.The
Tokenlocation supports Header, Cookie, Query parameter (GET), and Form parameter (POST). If you select Header as theTokenlocation, you must also specify the Parameter Name and Remove Prefix. When Function Compute retrieves the token, it removes the prefix specified in Remove Prefix.
In the JWT Claim Conversion section, specify the claim destination, the original claim names, and the new parameter names that will be passed to the function.
The mapping parameter location can be a Header, Cookie, or Form parameter (POST).

Set the request matching mode.
Match All: All HTTP requests require JWT validation.
Whitelist Mode: Requests for paths in the Whitelist of Request Paths bypass JWT validation. All other requests require it.
Blacklist Mode: Only requests for paths in the Blacklist of Request Paths require JWT validation. All other requests bypass it.
Whitelist Mode and Blacklist Mode support the following two matching modes:
Exact match
The request path must be an exact match to the specified path. For example, if you set Blacklist of Request Paths to /a, requests to the path /a require JWT validation, but requests to the path /a/ do not.
Fuzzy match
You can use a wildcard character (*) at the end of a path. For example, if you set Blacklist of Request Paths to /login/*, all requests to paths that start with /login/ (such as /login/a and /login/b/c/d) require JWT validation.
Step 2: Verify the configuration
Use a testing tool, such as Postman, to verify that you can access the HTTP service. Configure the access address, token, and other information based on the HTTP trigger's JWT configuration.
Use the X.509 PEM-formatted private key that you generated in Step 1: Configure JWT authentication to issue a JWT token. The following steps use Python as an example to demonstrate how to generate a token by using a local script.
Install the PyJWT module.
pip install 'PyJWT>=2.0'Run the following Python script locally to generate a JWT token.
import jwt import time private_key = """ -----BEGIN PRIVATE KEY----- <The private key in X.509 PEM format that you generated in Step 1> -----END PRIVATE KEY----- """ headers = { "alg": "RS256", "typ": "JWT" } payload = { "sub": "1234567890", "name": "John Snow", "iat": int(time.time()), # The time when the token was issued. "exp": int(time.time()) + 60 * 60, # Set the token to expire in one hour. } encoded = jwt.encode(payload=payload, key=private_key.encode(), headers=headers) print("Generated token: %s" % encoded)
Use Postman to verify access to the HTTP service.
On the Trigger tab of the function details page, obtain the public access address of the HTTP trigger and paste it into the URL field in Postman.
On the Headers tab in Postman, configure the token parameters and click Send. The following example shows the token configuration.
Parameter
Value
Description
Key
AuthenticationThe parameter name configured in JWT Token Configuration.
Value
Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9uIFNub3ciLCJhZG1pbiI6dHJ1ZSwiZXhwIjo0ODI5NTk3NjQxfQ.eRcobbpjAd3OSMxcWbmbicOTLjO2vuLR9F2QZMK4rz1JqfSRHgwQVqNxcfOIO9ckDMNlF_3jtdfCfvXfka-phJZpHmnaQJxmnOA8zA3R4wF4GUQdz5zkt74cK9jLAXpokwrviz2ROehwxTCwa0naRd_N9eFhvTRnP3u7L0xn3ll4iOf8Q4jS0mVLpjyTa5WiBkN5xi9hkFxd__p98Pah_Yf0hVQ2ldGSyTtAMmdM1Bvzad-kdZ_wW0jcctIla9bLnOo-Enr14EsGvziMh_QTZ3HQtJuToSKZ11xkNgaz7an5de6PuF5ISXQzxigpFVIkG765aEDVtEnFkMO0xyPGLgThe prefix specified in JWT Token Configuration, followed by the JWT token. The example value assumes that the prefix is set to
Bearer.ImportantThe token value in the request header must start with the exact prefix and space that you configured for Remove Prefix in the JWT Token Configuration section. Otherwise, the trigger fails to parse the token and returns an
invalid or expired jwterror.