Add Custom Filters

Filters are set of execution points in the request and response flow that intercept the request before it goes to the backend service and intercepts the response before forwarding to the client. Filters are applied to all the APIs exposed via Microgateway. Custom filter can be engaged to Microgateway runtime using the Microgateway toolkit. If there is a common functionality required by all the APIs exposed via the Microgateway then custom filter written in ballerina language can be used for that

How to add a custom filter

Filters can be defined in the deployment-config.toml file in the project conf (<PROJECT_HOME>/conf) folder. This project is the Microgateway project which is generated by executing the micro-gw init <PROJECT_NAME> command. Filter has the following methods to intercept the request and the response. Filter name can be any valid name and it is mandatory to have the filterRequest and filterRequest methods in the filter object.

Info

It is written in Ballerina 1.2.x so follow API docs in Ballerina documentation for language guide.

import ballerina/http;

public type CustomFilter object {

    public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns boolean {
        return true;
    }

    public function filterResponse(http:Response response, http:FilterContext context) returns boolean {
        return true;
    }
}      
  1. Write the custom filter logic in ballerina language. And save the content in a file with a .bal extension.

    
    import ballerina/http;
    
    public type CustomFilter object {
    
        public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns boolean {
            //Check if particular header present in the request. If header is present allow th request otherwise block the request.
            if(request.hasHeader("X-Auth")) {
                return true;
            }
            //If header is missing responds to the client.
            http:Response resp = new;
            resp.setTextPayload("X-Auth header is missing in the request");
            var result = caller->respond(resp);
            return false;
        }
    
        public function filterResponse(http:Response response, http:FilterContext context) returns boolean {
            return true;
        }
    };             
    

  2. Copy the implemented .bal file into the <PROJECT_HOME>/extensions folder.

  3. Define the custom filter in the deployment-config.toml as in below. Position starts from index 1.

    [[filters]]
        name = "CustomFilter"
        position = 1
    

  • name: Name of the filter object defined in the .bal file. Ex: CustomFiler

  • position: The poistion of the filter to be engaged. By default microgateway has the following set of filters. By defining the position it can engage the custom filter in between any default filter chain

    • gRPC Filter:Filter to handle gRPC backend services.

    • Pre Authentication Filter: Filter to prepare the request prior to authentication checks

    • Authentication Filter:Handles the authentication based on the different auth types. For ex: OAuth2, Basic and etc

    • Authorization Filter:Handles the Authorization

    • Validation Request Filter:Handles the open API schema validation for the request

    • Throttle Filter:Handles the rate limiting capabilities

    • Analytics Filter:Capture and publish analytics realted dat to analytics server

    • Validation Response Filter:Handles the open API schema validation for the response

    • Extension Filter:Common filter that can be used to customize error messages for authentication,throttling failure releated scenarios

4.Then build the project. Custom filter will be engaged in the runtime.

Skip endpoints for custom filters

To skip filters for health, token, and other similar APIs you can use the filter implementation given below.

  1. Add the following inside the filterRequest and filterResponse methods.
    string SKIP_ALL_FILTERS = "skip_filters";
        if (context.attributes.hasKey(SKIP_ALL_FILTERS) && <boolean>context.attributes[SKIP_ALL_FILTERS]) {
        return true;
        }
  2. To set the filter position parameter, go to the deployment.toml file and add the configuration given below.

    [[filters]]
      name = "TestFilter"
      position = 2

    Note

    If the custom filter chain is prior to the pre_authn_filter, then the context will not have the SKIP_ALL_FILTERS value set. Therefore, set the custom filter position to 2 or greater.

  3. A sample filter implementation is shown below.

    import ballerina/http;
    public type TestFilter object {
    public function filterRequest(http:Caller caller, http:Request request, http:FilterContext context) returns boolean {
        string SKIP_ALL_FILTERS = "skip_filters";
        if (context.attributes.hasKey(SKIP_ALL_FILTERS) && <boolean>context.attributes[SKIP_ALL_FILTERS]) {
        return true;
    }
    request.setHeader("customRequestHeader1", "Value1");
    return true;
    }
    public function filterResponse(http:Response response, http:FilterContext context) returns boolean {
        string SKIP_ALL_FILTERS = "skip_filters";
        if (context.attributes.hasKey(SKIP_ALL_FILTERS) && <boolean>context.attributes[SKIP_ALL_FILTERS]) {
        return true;
        }
    response.setHeader("customResponseHeader1", "Value2");
    return true;
    }
    };

Top