You can configure JSON Web Token (JWT) authentication for HTTP triggers in Function Compute. This way, only clients with valid tokens are allowed to access triggers. This helps improve HTTP security by blocking unauthorized or malicious access.
Background
Overview
Function Compute allows you to enable JWT authentication for HTTP triggers. JWT (RFC 7519) is an easy-to-use and token-based method to authenticate requests. User status information is stored in tokens provided by clients. Functions or servers do not store tokens. Therefore, this method is particularly suitable for serverless applications. Function Compute can use the public JSON Web Key Set (JWKS) that is configured for an HTTP trigger to perform JWT authentication on HTTP requests. Function Compute forwards claims
as parameters to functions based on configurations of the HTTP trigger. This way, request authentication is not required in functions, and you can focus on business logic. For more information about the authentication process and basic information about tokens
in JWT, see JWT-based authentication and Introduction to JSON Web Tokens.
JWT authentication process
The preceding figure shows the workflow of JWT authentication for HTTP triggers in Function Compute. In the process, an asymmetric encryption algorithm is used. The following items describe the process details:
The client sends an authentication request to a custom authentication service. In most cases, the username and password of a client user are specified in the request.
The custom authentication service reads and verifies authentication information, such as the username and password, in the request. After the request passes the verification, the authentication service uses a private key to generate a standard
token
.The custom authentication service forwards the response that contains the
token
to the client. The client caches thetoken
to an on-premises machine.The client sends a business request that contains the
token
to the HTTP trigger.The HTTP trigger uses a configured public key to verify the
token
in the request.After the verification is passed, the request is passed to the protected function.
The protected function processes and returns a response.
The HTTP trigger forwards the business response to the client.
Before you start
Create a service. For more information, see Create a service.
Create an HTTP function. For more information, see Create a function.
Limits
You can generate and distribute JWTs based on your business requirements. Function Compute authenticates the JWTs by using the public JWKS configured for the trigger.
A JSON Web Key (JWK) that does not have
kid
(key ID) is supported.A token can be read from a
header
, thequery
parameter (by using the GET method), the form parameter (by using the POST method), or acookie
.You can forward
claims
asheaders
,query
parameters (by using the GET method), forms parameters (by using the POST method), andcookies
to functions.You can configure a JWKS for an HTTP trigger. After the JWKS is configured, the system searches the JWKS for a public JWK that has the same
kid
as the kid in thetoken
and uses the public JWK to verify the signature of thetoken
. The JWKS of a trigger is allowed to have at most one JWK whosekid
does not exist or is set to an empty string.The following table lists the algorithms that are supported by the JWT of Function Compute.
Signature algorithm
alg value
RSASSA-PKCS1-V1_5
RS256, RS384, or RS512
RSASSA-PSS
PS256, PS384, or PS512
Elliptic Curve (ECDSA)
ES256, ES384, or ES512
HMAC
HS256, HS384, or HS512
EdDSA
EdDSA
ImportantThe hash-based message authentication code (HMAC) signature algorithm uses symmetric encryption, which provides weak security. We recommend that you use an asymmetric encryption algorithm for enhanced security.
If you use an asymmetric encryption algorithm, you need to include information only about public keys, instead of private keys in your JWT, for security purposes.
We recommend that you use HTTPS to protect sensitive information such as
tokens
in requests to prevent token leakage.
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 Modify in the Actions column of the HTTP trigger.
In the Modify Trigger panel, configure the following parameters and click OK.
Set Authentication Method to JWT Authentication.
Configure JWKS.
To configure JWT authentication for an HTTP trigger, you must provide a valid JWKS. You can manually generate a JWKS, or search by JSON Web Key generator in a web browser to use an online generator, such as mkjwk.org. If you have a key in the Privacy Enhanced Mail (PEM) format, you can use a tool such as jwx to convert the key to the JWKS format.
In this example, mkjwk.org is used to generate a JWKS. On the page for generating a JWKS, set Show X.509 to Yes to view private keys. You need to use the private key to issue a JWT. Keep the private key secure. You can copy the content of the public key to the keys array of JWKS in the Function Compute console. The following figure shows the details.
Sample code:
{ "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 position and name of the
token
.You can set the Read Position parameter of the
token
to Header, Cookie, Query Parameters, or Form Parameters. If you set the Read Position parameter of atoken
to Header, you must specify the Parameter Name and Remove Prefix parameters. When Function Compute obtains the token, the prefix that is specified by the Remove Prefix parameter is deleted.ImportantWhen you configure the Remove Prefix parameter, check whether spaces exist after the prefix. We recommend that you add a space after the specified prefix, for example,
Bearer
.In the JWT Claim Conversion section, select the position to pass parameters to the function, the original name of the parameter, and the new name of the parameter after the parameter is passed to the function.
You can set the Mapping Parameter Position parameter to Header, Cookie, Query Parameters, or Form Parameters.
Specify the request matching mode.
Match All: All HTTP requests must be verified by using JWT.
Whitelist Mode: HTTP requests that are sent from the paths specified in Whitelist of Request Paths are not authenticated by using JWTs. Other requests are authenticated by using JWTs.
Blacklist Mode: HTTP requests that are sent from the paths specified in Blacklist of Request Paths are authenticated by using JWTs. Other requests are not authenticated by using JWTs.
Whitelist Mode and Blacklist Mode support the following matching modes:
Exact matching
A path is matched only if it is exactly the same as the specified path. For example, if you set Blacklist of Request Paths to /a, JWT authentication is required for requests that are sent from /a. JWT authentication is not required for requests that are sent from /a/.
Fuzzy matching
You can set the value to a path that is appended with an asterisk (*) as the wildcard. For example, if you set the Blacklist of Request Paths parameter to /login/*, JWT authentication is required for requests that are sent from the paths prefixed with /login/, such as /login/a and /login/b/c/d.
Step 2: Verify JWT configurations of the HTTP trigger
This section describes how to verify whether HTTP services can be accessed as expected by using a tool based on the JWT configurations of your HTTP trigger. In this section, Postman is used..
Use the private key in the X.509 PEM format generated in Step 1 as the private key to issue a JWT. The following steps use Python as an example to demonstrate the process of generating a token by using a local script.
Install the PyJWT module.
pip install PyJWT
Run the following Python script on your on-premises machine to generate a JWT:
import jwt import time private_key = """ -----BEGIN PRIVATE KEY----- <Use the private key in the X.509 PEM format 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 validity period of the token to 1 hour. } encoded = jwt.encode(payload=payload, key=private_key.encode(), headers=headers) print("Generated token: %s" % encoded)
Use Postman to check whether the HTTP services can be accessed.
On the Trigger Management (URL) tab of the function that you want to manage, obtain the Internet endpoint of the HTTP trigger. Then, enter the endpoint in the address bar of Postman.
Configure the token parameters on the Headers tab in Postman and click Send to send the request. The following table describes the configuration of the token.
Name
Example
Description
Key
Authentication
The name of the token that you specified in the JWT Token Configuration section.
Value
Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9uIFNub3ciLCJhZG1pbiI6dHJ1ZSwiZXhwIjo0ODI5NTk3NjQxfQ.eRcobbpjAd3OSMxcWbmbicOTLjO2vuLR9F2QZMK4rz1JqfSRHgwQVqNxcfOIO9ckDMNlF_3jtdfCfvXfka-phJZpHmnaQJxmnOA8zA3R4wF4GUQdz5zkt74cK9jLAXpokwrviz2ROehwxTCwa0naRd_N9eFhvTRnP3u7L0xn3ll4iOf8Q4jS0mVLpjyTa5WiBkN5xi9hkFxd__p98Pah_Yf0hVQ2ldGSyTtAMmdM1Bvzad-kdZ_wW0jcctIla9bLnOo-Enr14EsGvziMh_QTZ3HQtJuToSKZ11xkNgaz7an5de6PuF5ISXQzxigpFVIkG765aEDVtEnFkMO0xyPGLg
The JWT value, which contains the value of the Remove Prefix parameter in JWT Token Configuration. In this example, the Remove Prefix parameter is set to
Bearer
.ImportantThe prefix and space of the JWT parameter in the request header must be the same as those of the Remove Prefix parameter in the JWT Token Configuration section. Otherwise, an error occurs when the trigger parses the token and reports the "invalid or expired jwt" error.
Perform JWT authentication with a custom domain name
The preceding figure shows that a custom domain name processes user requests before an HTTP trigger processes the requests. JWT authentication is performed on the HTTP trigger. This section describes how to use JWT authentication in scenarios in which custom domain names are configured.
Custom domain names with no rewrite policies configured
If routes are configured for a custom domain name with no rewrite policy configured, the paths of the incoming HTTP requests are the paths of the custom domain name.
For example, the following table describes the route rule for the custom domain name www.fc-jwt.com
. The value of the Blacklist of Request Paths parameter in the JWT configuration of the HTTP trigger for the jwt-demo
function is /fc-jwt/auth/*.
Path | Service name | Function name | Version |
/fc-jwt/* | jwt | jwt-demo | 1 |
If the URL of a request is /fc-jwt/auth/aliyun, the HTTP trigger verifies the HTTP request because the path of the request matches the value that is specified in the Blacklist of Request Paths parameter.
Custom domain names with rewrite policies configured
If routes are configured for the custom domain name with a rewrite policy configured, the paths of the incoming HTTP requests are the rewritten URLs. For more information about the rewrite feature for custom domain names, see Configure rewrite policies (in public review).
For example, you have configured a route rule for the custom domain name www.fc-jwt.com
as described in the following table. In the JWT configurations of the HTTP trigger for the jwt-demo
function, the Blacklist of Request Paths parameter is set to /fc-jwt/auth/*, and a wildcard rewrite policy is configured. The match rule is /fc-jwt/*
, and the replacement rule is /$1
.
Path | Service name | Function name | Version |
/fc-jwt/* | jwt | jwt-demo | 1 |
If the URL of a request is /fc-jwt/auth/aliyun, the rewritten URL is /auth/aliyun. For more information about the wildcard rewrite rules, see Configure rewrite policies (in public review). The HTTP trigger does not verify the request. In this case, the path of the request to the HTTP trigger is /auth/aliyun and does not match the value of the Blacklist of Request Paths parameter.
If you set the Blacklist of Request Paths parameter to /auth/*, the HTTP trigger performs JWT authentication on requests whose URL is /fc-jwt/auth/aliyun.