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
Situation Awareness
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

Building a Program

Updated on 2024-11-15 GMT+08:00

Creating an API group

Before creating a function and adding an event source, create an API group to store and manage APIs.

NOTE:

Before enabling APIG functions, buy a gateway by referring to Buying a Gateway.

  1. Log in to the APIG console, choose API Management > API Groups in the navigation pane, and click Create API Group in the upper right.
  2. Select Create Directly, set the group information, and click OK.

    • Name: Enter a group name, for example, APIGroup_test.
    • Description: Enter a description about the group.

Creating a Custom Authentication Function

Frontend custom authentication means APIG uses a function to authenticate received API requests. To authenticate API requests by using your own system, create a frontend custom authorizer in APIG. Create a FunctionGraph function with the required authentication information. Then use it to authenticate APIs in APIG.

This section uses the header parameter event["headers"] as an example. For the description about request parameters, see Request Parameter Code Example.

  1. In the left navigation pane of the management console, choose Compute > FunctionGraph to go to the FunctionGraph console. Then choose Functions > Function List in the navigation pane.
  2. Click Create Function.
  3. Set the function information, and click Create Function.

    • Template: Select Create from scratch.
    • Function Type: Select Event Function.
    • Function Name: Enter a function name, for example, apig-test.
    • Agency: Select Use no agency.
    • Runtime: Select Python 2.7.

  4. On the function details page that is displayed, click the Code tab and copy the example request parameter code to the online editor, and click Deploy.
  5. Click Configure Test Event, and select an event template. Modify the template as required, and click Create. In this example, add "auth":"abc" to "headers".

    Figure 1 Configuring a test event

  6. Click Test. If the result is Execution successful, the function is successfully created.

    Figure 2 Viewing the execution result

Creating a Custom Authorizer

Create a custom authorizer in APIG and connect it to the frontend custom authentication function.

  1. In the left navigation pane of the management console, choose Middleware > API Gateway to go to the APIG console. In the navigation pane, choose API Management > API Policies. On the Custom Authorizers tab, click Create Custom Authorizer.
  2. Configure basic information about the custom authorizer according to the following figure.

    • Name: Enter a name, for example, Authorizer_test.
    • Type: Select Frontend.
    • Function URN: Select apig-test.
      Figure 3 Creating a custom authorizer

  3. Click OK.

Creating a Backend Service Function

APIG supports FunctionGraph backends. After you create a FunctionGraph backend API, APIG will trigger the relevant function, and the function execution result will be returned to APIG.

  1. Create a service function by referring to Creating a Custom Authentication Function. The function name must be unique.
  2. On the Code tab of the function details page, copy the following code to the online editor, and click Deploy.

    # -*- coding:utf-8 -*-
    import json
    def handler (event, context):
        body = "<html><title>Functiongraph Demo</title><body><p>Hello, FunctionGraph!</p></body></html>"
        print(body)
        return {
            "statusCode":200,
            "body":body,
            "headers": {
                "Content-Type": "text/html",
            },        
            "isBase64Encoded": False
        }

Request Parameter Code Example

The following are the requirements you must meet when developing FunctionGraph functions. Python 2.7 is used as an example.

The function must have a clear API definition. Example:

def handler (event, context)
  • handler: name of the entry point function. The name must be consistent with that you define when creating a function.
  • event: event parameter defined in JSON format for the function.
  • context: runtime information provided for executing the function. For details, see SDK APIs.
event supports three types of request parameters in the following formats:
  • Header parameter: event["headers"]["Parameter name"]
  • Query string: event["queryStringParameters"]["Parameter name"]
  • Custom user data: event["user_data"]
The three types of request parameters obtained by the function are mapped to the custom authentication parameters defined in APIG.
  • Header parameter: Corresponds to the identity source specified in Header for custom authentication. The parameter value is transferred when the API that uses custom authentication is called.
  • Query string: Corresponds to the identity source specified in Query for custom authentication. The parameter value is transferred when the API that uses custom authentication is called.
  • Custom user data: Corresponds to the user data for custom authentication. The parameter value is specified when the custom authorizer is created.
  • The function response cannot be greater than 1 MB and must be in the following format:
    {     "statusCode":200,
          "body": "{\"status\": \"allow\", \"context\": {\"user\": \"abc\"}}" 
     }

The body field is a character string, which is JSON-decoded as follows:

{
	"status": "allow/deny",
	"context": {
		"user": "abc"
	}
}

The status field is mandatory and is used to identify the authentication result. The authentication result can only be allow or deny. allow indicates that the authentication is successful, and deny indicates that the authentication fails.

The context field is optional and can only be key-value pairs. The key value cannot be a JSON object or an array.

The context field contains custom user data. After successful authentication, the user data is mapped to the backend parameters. The parameter name in context is case-sensitive and must be the same as the system parameter name. The parameter name must start with a letter and can contain 1 to 32 characters, including letters, digits, hyphens (-), and underscores (_).

Example Header Parameter

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event["headers"].get("auth")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"success"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)

Example Query String

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event["queryStringParameters"].get("test")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"abcd"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)

Example User Data

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event.get("user_data")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"abcd"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)

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