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

Creating a Backend Custom Authorizer

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

To use your own API calling authentication system, create a custom authorizer.

Custom authorizers are classified into the following types:

  • Frontend: APIG uses a custom authentication function to authenticate API requests.
  • Backend: The backend service of an API uses a custom authentication function to authenticate requests forwarded by APIG.

This section describes how to create a backend custom authorizer. Ensure that you have created a function backend before using it for a custom authorizer.

Figure 1 Schematic diagram of backend custom authentication

The following figure shows the process of calling APIs through custom authentication.

Figure 2 Calling APIs through custom authentication

Constraints

FunctionGraph is required for custom authorizers. If FunctionGraph is unavailable in the selected region, custom authorizers are not supported.

Creating a Function for Backend Custom Authentication

  1. Log in to the FunctionGraph console.
  2. In the navigation pane on the left, choose Functions > Function List.
  3. Click Create Function and create a function based on the following table.

    Table 1 Configuring the function

    Parameter

    Description

    Create With

    Select Create from scratch.

    Function Type

    Type of the function. 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. Using naming rules facilitates future search.

    Enterprise Project

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

    Agency

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

    Runtime

    Python 2.7 is used as an example.

  4. Click Create Function.
  5. After the function is created, go to the function details page.

    The function code must meet the following requirements:

    • The custom user data contained in the function code must be in the following format: event["user_data"].
    • The custom user data corresponds to the user data defined for the custom authorizer. You can define the user data in any format.
    • The response of the function cannot be greater than 1 MB and must be displayed 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 statusCode field is mandatory. If FunctionGraph is running properly and the code of the function complies with specifications, the value of statusCode is the response code of the function.
        • If response code is not 200, APIG considers that the function is abnormal and returns error code 500 and error information Internal server error.
        • When the relaxed mode of the custom authorizer is turned on and the function fails to connect or returns a 500 or 503 code, the authorizer does not check the status field in the body field. Instead, it will immediately return a message indicating that the API was successfully invoked. And the context field obtained from the function code will be empty.
      • 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. It can be key-value pairs, but the key value cannot be a JSON object or an array. If the gateway supports the authorizer_context_support_num_bool feature, the key value can be a number or a Boolean value.

        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 in context must start with a letter and contain 1 to 32 characters, including uppercase letters, lowercase letters, digits, underscores (_), and hyphens (-).

        After successful backend authentication, the value abc of user in context is mapped to the test parameter in the Header location of backend requests and passed to the backend service.

    Example user data:

    # -*- coding:utf-8 -*-
    import json
    import base64
    def handler(event, context):
        exampleuserdata=base64.b64encode(event["user_data"])
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":exampleuserdata
                }
            })   
        }
        return json.dumps(resp)

  6. Test the function. In the Configure Test Event dialog box, select blank-template, and set the following test event:

    {"user_data": "123"}

    Click Save. Then click Test.

    If the execution result is Success, the test is successful.

    Next, go to the APIG console to create a backend custom authorizer.

Creating a Backend Custom Authorizer

Before creating a backend custom authorizer, ensure that the function backend used for backend custom authentication has been created. Otherwise, create a function API first. For details, see Creating a Function for Backend Custom Authentication.

  1. Go to the APIG console.
  2. Select a dedicated gateway at the top of the navigation pane.
  1. In the navigation pane, choose API Management > API Policies.
  2. On the Custom Authorizers page, click Create Custom Authorizer. Configure the custom authorizer parameters based on the following table.

    Table 2 Parameters for creating a custom authorizer

    Parameter

    Description

    Name

    Authorizer name. It can contain 3 to 64 characters and must start with a letter. Only letters, digits, and underscores (_) are allowed.

    Type

    Select Backend.

    Function URN

    Select a function backend for custom authentication. Only function backends in the Deployed state can be selected.

    Version/Alias

    Select a function version or alias. For details, see FunctionGraph User Guide.

    Max. Cache Age (s)

    The time for caching authentication results.

    The value ranges from 0s to 3,600s. 0 indicates that authentication results will not be cached.

    Relaxed Mode

    • When this option is enabled, APIG accepts client requests even when FunctionGraph cannot connect or returns an error code starting with "5". If there is a retry request, the last returned result is used.
    • When this option is enabled, if a custom authorizer is used for backend authentication of an API, the value of the backend authentication parameter is empty.

    The relaxed mode has security risks. Therefore, exercise caution when selecting this mode.

    Identity Sources

    Request parameters used for authentication.

    This parameter is mandatory only if you set Type to Frontend, and Max. Cache Age (s) is greater than 0. When the cache is used, this parameter is used as a search criterion to query authentication results.

    Send Request Body

    Determine whether to send the body of each API request to the authentication function. If you enable this option, the request body will be sent to the authentication function in the same way as the headers and query strings.

    User Data

    Customized request parameters to be used together with Identity Sources when APIG invokes a function. The value contains 1 to 2,048 characters.

  3. Click OK.

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