Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ API Gateway/ Best Practices/ API Authentication/ Configuring Two-factor Authentication (App + Custom)

Configuring Two-factor Authentication (App + Custom)

Updated on 2025-01-21 GMT+08:00

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 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.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback