Help Center> API Gateway> Developer Guide (Kuala Lumpur Region)> Creating a Function for Frontend Custom Authentication
Updated on 2022-08-12 GMT+08:00

Creating a Function for Frontend Custom Authentication

Scenarios

Custom authentication is supported for both frontend and backend requests. For frontend custom authentication, API Gateway uses a function to authenticate received API requests. For backend custom authentication, the backend service invokes another function to authenticate the API requests forwarded by API Gateway.

API requests can be authenticated using a custom authorizer. You need to create a FunctionGraph function for frontend custom authentication and define the required authentication information in the function. The function then serves as a custom authentication backend to authenticate requests for the API.

This section describes how to encapsulate a function into a "custom authorizer" and the important operations that need to be noted.

Figure 1 Schematic diagram of frontend custom authentication

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

Figure 2 Calling APIs by using custom authentication

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

Procedure

  1. Create a function in FunctionGraph.

    The function code must meet the following requirements (Python 2.7 is used as an example):
    • The function code has defined three types of request parameters in the following formats:
      • Header parameters: event["headers"]["Parameter name"]
      • Query parameters: 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 API Gateway.
      • 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 parameter: 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 authentication system is created.
    • 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 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 (_). After successful frontend authentication, the value abc of user in context is mapped to the test parameter in the Header location of backend requests.

    Example header parameters:

    # -*- coding:utf-8 -*-
    import json
    def handler(event, context):
        if event["headers"].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 query parameters:

    # -*- 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)

  2. Test the function. In the Configure Test Event dialog box, select apig-event-template, edit the test event, and click Save. Then click Test.

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

    Next, you need to go to the API Gateway console to create a frontend custom authorizer.

Follow-Up Operations

Create a custom authorizer for frontend authentication on the API Gateway console.