هذه الصفحة غير متوفرة حاليًا بلغتك المحلية. نحن نعمل جاهدين على إضافة المزيد من اللغات. شاكرين تفهمك ودعمك المستمر لنا.

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/ Developing a Custom Authorizer with FunctionGraph

Developing a Custom Authorizer with FunctionGraph

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

Scenario

In addition to IAM and app authentication, APIG also supports custom authentication with your own authentication system, which can better adapt to your business capabilities.

Custom authentication is implemented using the FunctionGraph service. You can create a FunctionGraph function so that APIG can invoke it to authenticate requests for your API. This section uses basic authentication as an example to describe how to implement custom authentication with FunctionGraph.

General Procedure

  1. Developing a Custom Authentication Function

    Create a function for custom authentication.

  2. Creating a Custom Authorizer

    Create a custom authorizer in APIG to connect the function.

  3. Creating a Custom Authentication API

    Create an API with Custom authentication mode.

  4. Setting the Error Response

    To include the context field of the function response in the API response result, modify the gateway response.

  5. Mapping Frontend Authentication Parameters to Backend Parameters

    Add a system parameter to transfer the context information returned by the function to the backend.

  6. Verifying the API

    Call the API and check whether the context information of the function is successfully returned.

Developing a Custom Authentication Function

Create a function on the FunctionGraph console by referring to Creating a Function for Frontend Custom Authentication.

Create a function on the FunctionGraph page according to the following table.

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

After the function is created, go to the function details page. On the Code tab page, copy the following code to index.py (if you are using a dedicated gateway, for which the authorizer_context_support_num_bool parameter has been enabled, the type of value in context can be boolean or number).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding:utf-8 -*-
import json
def handler(event, context):
# If the authentication information is correct, the username is returned.
    if event["headers"]["authorization"]=='Basic dXN****cmQ=':
        return {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user_name":"user1"
                }
            })
        }
    else:
        return {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
                "context":{
                    "code": "1001",  
                    "message":"incorrect username or password",
                    "authorizer_success": "false"  
                }
            })
        }

Creating a Custom Authorizer

On the APIG console, choose API Policies > Custom Authorizers, click Create Custom Authorizer page, set Type to Frontend, and select the created function for Function URN.

Creating a Custom Authentication API

On the APIs page of the APIG console, create an API by referring to Creating an API. Set the authentication mode to Custom, and select the custom authorizer created in the preceding section. After modifying the API, publish it.

Setting the Error Response

If incorrect authentication information is carried in a request for the API, the response is displayed as follows:

1
{"error_msg":"Incorrect authentication information: frontend authorizer","error_code":"APIG.0305","request_id":"36e42b3019077c2b720b6fc847733ce9"}

To return the field in the function's context as the API response (if you are using a dedicated gateway, for which the authorizer_context_support_num_bool parameter has been enabled, the type of value in context can be boolean or number), modify the gateway response template. On the details page of the group to which the API belongs, navigate to the Gateway Responses area on the Gateway Information tab, and click Edit. Change the status code to 401, modify the response template with the following code, and click OK (no need to add double quotes for variables of the boolean or number type):

1
{"code":"$context.authorizer.frontend.code","message":"$context.authorizer.frontend.message", "authorizer_success": "$context.authorizer.frontend.authorizer_success"}

After the modification, if incorrect authentication is transferred when calling the API, the status code 401 is returned and the response result is as follows:

1
 {"code":"1001","message":"incorrect username or password","authorizer_success": "false"}

Mapping Frontend Authentication Parameters to Backend Parameters

If the authentication is successful, the context information returned by the function can be transferred to the backend of the API. To do this, perform the following configurations:

On the APIs page, choose More > Edit in the row that contains the API, and go to the Define Backend Request page. Add a system parameter, specify the parameter type as Frontend authentication parameter, set the parameter name to the content of the context field in the function response, and set the name and location of the backend parameter to which you want to the map the frontend authentication parameter.

Verifying the API

After modifying the API, publish it again. If the authentication information carried in a request for the API is correct, the response result contains the X-User-Name header field whose value is the same as that of user_name in the context field of the authentication function.

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