Help Center/ API Gateway/ Best Practices/ API Authentication/ Configuring Two-factor Authentication (App + Custom)
Updated on 2025-03-06 GMT+08:00

Configuring Two-factor Authentication (App + Custom)

Scenario

Two-factor authentication allows you to customize an API authentication policy together with the app or IAM authentication. This section describes how to create an API that uses two-factor authentication (app + custom).

Advantages

You can use a custom authorizer to ensure API security.

Restrictions

The custom authorizer depends on FunctionGraph. Before creating a custom authorizer, you need to create a function.

General Procedure

  1. Create a function.

    The function will be used for custom authentication.

  2. Create a custom authorizer.

    Set the authorizer type to Frontend, and select the function created in the previous step.

  3. Create an API.

    Set authentication mode to App, enable Two-Factor Authentication, and select the custom authorizer created in the previous step.

  4. Create a credential.

    APIs that use app authentication require a credential to call. Create a credential to generate an ID and key/secret pair.

  5. Bind the credential to the created API.

    APIs that use app authentication can be called only with bound credentials.

  6. Verify the API.

    Call the API to check whether two-factor authentication is configured successfully.

Implementation Procedure

  1. Log in to the FunctionGraph console. On the Dashboard page, click Create Function.

    1. Set the parameters according to the following table, and click Create Function.
      Table 1 Function configuration

      Parameter

      Description

      Create With

      Select Create from scratch.

      Function Type

      Default: Event Function

      Region

      Select the same region as that of APIG.

      Project

      Projects group and isolate resources (including compute, storage, and network resources) across physical regions. A default project is provided for each Huawei Cloud region, and subprojects can be created under each default project. Users can be granted permissions to access all resources in a specific project. The selected region is used by default.

      Function Name

      Set this name as planned.

      Enterprise Project

      Enterprise projects group and manage resources across regions. Resources in enterprise projects are logically isolated. Select default.

      Agency

      An agency that delegates FunctionGraph to access other cloud services. For this example, select Use no agency.

      Runtime

      Select Python 3.9.

    2. After the function is created, go to the function details page. On the Configuration tab, choose Environment Variables in the left pane, and click Edit Environment Variable > Add.
      Table 2 Configuring environment variables

      Parameter

      Description

      Key

      Name of the environment variable. Add the token and test environment variables. token is a header for identity authentication, and test is for parameter query.

      Value

      Environment variable value. Set the value of token to Basic dXNlcjE6cGFzc3dvcmQ= and test to user@123.

      Encrypted

      If enabled, the environment variable value is encrypted and displayed as an asterisk (*). During parameter transmission, the key value is also encrypted. Encrypt the sensitive token key in this example.

    3. On the Code tab, copy the following code to index.py, and click Deploy. For details about coding, see Creating a Function for Frontend Custom Authentication.
      # -*- coding:utf-8 -*-
      import json
      def handler(event, context):
          testParameter = context.getUserData('test');
          userToken = context.getUserData('token');
          if event["headers"].get("token") == userToken and event["queryStringParameters"].get("test") == testParameter:
              resp = {
                  'statusCode': 200,
                  'body': json.dumps({
                      "status":"allow",
                      "context":{
                          "user":"auth success"
                      }
                  })
              }
          else:
              resp = {
                  'statusCode': 401,
                  'body': json.dumps({
                      "status":"deny",
                  })   
              }
          return json.dumps(resp)
    4. Configure a test event to debug the code.
      1. Select Configure Test Event from the drop-down list and configure a test event. Set the following code as the test event. The parameter values in the test event must be the same as those of the environment variables.
        {
            "headers": {
                "token": "Basic dXNlcjE6cGFzc3dvcmQ="
            },
            "queryStringParameters": {
                "test": "user@123"
            }   
        }

      2. Click Test. If the following information is displayed, the code debugging is successful.

      3. Click Deploy.

  2. Go to the APIG console, and choose API Management > API Policies.

    On the Custom Authorizers tab, create a custom authorizer.
    Table 3 Custom authorizer configuration

    Parameter

    Description

    Name

    Set this name as planned.

    Type

    Select Frontend.

    Function URN

    Click Select and select the created function.

    Version/Alias

    Version is selected by default.

    Max. Cache Age (s)

    30

    Identity Sources

    Set two identity sources: header token and query string test.

  3. Choose API Management > APIs, and click Create API > Create API.

    1. Configure the frontend information according to the following table.
      Table 4 Frontend configuration

      Parameter

      Description

      API Name

      Enter an API name.

      Group

      Group to which the API belongs. The default value is DEFAULT.

      URL

      Method: Request method of the API. Set this parameter to GET.

      Protocol: Request protocol of the API. Set this parameter to HTTPS.

      Subdomain Name: The system automatically allocates a subdomain name to each API group for internal testing. The subdomain name can be accessed 1,000 times a day.

      Path: Path for requesting the API. Enter /api/two_factor_authorization.

      Gateway Response

      Select a response to be displayed if the gateway fails to process an API request.

      The default gateway response is default.

      Authentication Mode

      API authentication mode. Set this parameter to App.

      Two-Factor Authentication

      Enable this option and select a custom authorizer.

    2. Click Next and set the backend type to Mock.

      Select a status code, set the response, and click Finish.

    3. Publish the API.

  4. In the navigation pane, choose API Management > Credentials.

    Click Create Credential, enter a credential name, and click OK.

  5. Bind the credential to the API.

    Click the credential name to go to the details page. In the APIs area, click Bind to APIs, select an API, and click OK.

  6. Verify the API.

    • Call the API on the debugging page of APIG to verify if two-factor authentication is configured successfully.

      Add test on the Parameters tab and add token on the Headers tab. Use the same parameter values set for the custom authentication function. If the server returns 200, the authentication is successful. If the parameter values are different, the server will return a 401 message indicating that the authentication fails.

    • Alternatively, call the API with a curl command. Download the JavaScript SDK first. To call the API, input a key and secret as well as the header and query string to generate a curl command, and then copy this command to your CLI for execution. For details, see curl in the API Gateway Developer Guide.