All Products
Search
Document Center

Function Compute:Configure JWT authentication for an HTTP trigger

Last Updated:May 17, 2024

Function Compute allows you to configure JSON Web Token (JWT) authentication for HTTP triggers to ensure that only clients with valid JWTs can access functions. This enhances security of HTTP services and effectively prevents unauthorized access and malicious attacks.

Background information

Introduction

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 implement JWT authentication on HTTP requests. Function Compute forwards claims to functions based on the 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

image

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 details of the process:

  1. The client sends an authentication request to a custom authentication service. In most cases, a username and password are specified in the request.

  2. The custom authentication service reads and verifies the 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.

  3. The custom authentication service forwards the response that contains the token to the client. The client caches the token to an on-premises machine.

  4. The client sends a business request that contains a token to the HTTP trigger.

  5. The HTTP trigger uses a configured public key to verify the token in the request.

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

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

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

Prerequisites

A function and an HTTP trigger are created. For more information, see Creates a function. and Step 1: Create a trigger.

Limits

  • You can generate and distribute JWTs in a way based on your business requirements. Function Compute authenticates the JWTs by using the public JWKS configured for the HTTP trigger.

  • A JSON Web Key (JWK) without kid (key ID) is supported.

  • A token can be read from a header, the query parameter (by using the GET method), the form parameter (by using the POST method), or a cookie.

  • You can forward claims as headers, query parameters (by using the GET method), forms parameters (by using the POST method), or cookies 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 with a kid that matches the kid in the token and uses this public JWK to verify the signature of the token. You can leave at most one JWK's kid of the JWKS of a trigger unspecified or 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

    Important
    • The hash-based message authentication code (HMAC) signature algorithm uses symmetric encryption. This encryption is less secure. 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 leaks.

Procedure

Step 1: Configure JWT authentication

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. In the lower part of the function details page, click the Configuration tab. In the left-side navigation pane, click Trigger. On the page that appears, find the HTTP trigger and click Modify in the Actions column.

  4. In the Modify Trigger panel, configure the following parameters and click OK.

    1. Set Authentication Method to JWT Authentication.

      image

    2. Configure JWKS.

      To configure JWT authentication for the HTTP trigger, you must provide a valid JWKS. You can generate a JWKS by yourself, or search by JSON Web Key generator in a web browser to obtain an online generator, such as mkjwk.org. If you have a key in the PEM format, you can use a tool such as jwx to convert the key to the JWKS format.

      This topic uses mkjwk.org as an example to describe how to generate a JWKS. In the example shown in the following figure, set Key Use to Signature, Algorithm to RS256, and Show X.509 to Yes, and then click Generate to generate a private key. In your code, you must use the private key to issue a JWT. Copy the content of the public key and paste the copied content in the JWKS input box in the console.

      image.png

      image

      The following sample code shows a configured JWKS:

      {
          "keys": [
              {
                  "alg": "RS256",
                  "e": "AQAB",
                  "kty": "RSA",
                  "n": "u1LWgoomekdOMfB1lEe96OHehd4XRNCbZRm96RqwOYTTc28Sc_U5wKV2umDzolfoI682ct2BNnRRahYgZPhbOCzHYM6i8sRXjz9Ghx3QHw9zrYACtArwQxrTFiejbfzDPGdPrMQg7T8wjtLtkSyDmCzeXpbIdwmxuLyt_ahLfHelr94kEksMDa42V4Fi5bMW4cCLjlEKzBEHGmFdT8UbLPCvpgsM84JK63e5ifdeI9NdadbC8ZMiR--dFCujT7AgRRyMzxgdn2l-nZJ2ZaYzbLUtAW5_U2kfRVkDNa8d1g__2V5zjU6nfLJ1S2MoXMgRgDPeHpEehZVu2kNaSFvDUQ",
                  "use": "sig"
              }
          ]
      }
    3. In the JWT Token Configuration section, select the position to read the token and the 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 Read Position of a token to Header, you must specify a prefix. Function Compute removes this prefix when obtaining the token.

      image

    4. 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 it is passed to the function.

      You can set Mapping Parameter Position to Header, Cookie, Query Parameter, or Form Parameters.

      image

    5. Set the request matching mode. The following matching modes are supported:

      • 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 match

        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 not sent from /a/.

      • Fuzzy match

        You can set the value to a path that is appended with an asterisk (*) as the wildcard. For example, if you set Blacklist of Request Paths to /login/*, requests that are sent from the paths prefixed with /login/, such as /login/a and /login/b/c/d, must be JWT authenticated.

Step 2: Verify JWT authentication

Enter information, such as the URL to be accessed and the token to be used, in a tool, such as Postman, to check whether the HTTP service can be accessed.

  1. Use the private key that is generated in Step 1: Configure JWT authentication to create a JWT.

  2. Use Postman to verify whether the HTTP service can be accessed as expected.

    1. Obtain the Internet URL from the Configuration > Trigger tab and enter the URL in Postman.

    2. Configure the token parameters on the Headers tab in Postman. The following table provides an example:

      Column

      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 header that is used to read the token. You must leave a space between the prefix to be removed and the token. The header part that excludes the prefix is used as the token.

    3. Click Send and view the returned information of the HTTP service. The following figure provides an example:

      image.png

      In the returned information, nametofunction indicates the name that is passed to the function by Claim.

FAQ

Why is "invalid or expired jwt" returned when I access a custom domain name after I enable JWT authentication for the domain name?

The message indicates that JWT authentication failed. The following items list the possible causes:

  • The signature or format of your token is invalid.

  • Your token has expired.

  • The key ID of your token does not match the JWKS that you configured for your custom domain name, or the matched JWK is not accurate.

Why is "the jwt token is missing" returned when I access a custom domain name after I enable JWT authentication for the custom domain name?

The message indicates that Function Compute cannot find the token based on the configurations of the JWT token of the custom domain name. Check whether the token is contained in the request or the read position or name is correctly specified. If you set the Read Position parameter in the JWT Token Configuration section to Header, you must add the value of the Remove Prefix parameter and leave a space between the value and the JWT token when you configure the token. Otherwise, an error is returned.

Am I charged for JWT authentication?

No, you are not charged for JWT authentication. By default, you are charged for gateway-related features provided by Function Compute based on the number of function invocations. Therefore, you are not charged for JWT authentication, regardless of whether you enable the feature.