Custom Policy in Mule 4

  • February 13, 2020

Custom Policy can be added at runtime to extend the functionality of a Mule application. You can apply custom policies to Mule applications at a Runtime level in CloudHub.

The following is an actual Custom Policy use case that will validate a department at policy level using the department Validator API.

The current workflow to get a working policy for Mule 4 that can be applied in the Anypoint Platform consists of the following steps:

  • Develop the policy
  • Package the policy
  • Upload the resulting policy assets to Exchange
  • Apply the policy to any API through the API Manager

Step 1: Develop the policy

The first step in developing a Custom Policy is setting up a project with the required files.

The easiest way to gather all your required files is to use the Maven Archetype. This archetype creates all the necessary files for you. Then, use Maven to package your Custom Policy into a deployable jar.

The details below, shown in Settings.xml, will generate the required archetype for a Custom Policy.

Develop the policy

Once Maven is configured:

  • Create a new directory where the Custom Policy project will live
  • Go to that directory in the command line
  • Execute the following command:

mvn -Parchetype-repository archetype:generate \

-DarchetypeGroupId=org.mule.tools \

-DarchetypeArtifactId=api-gateway-custom-policy-archetype \

-DarchetypeVersion=1.1.0 \

-DgroupId=${orgId} \

-DartifactId=${policyName} \

-Dversion=1.0.0-SNAPSHOT \

-Dpackage=mule-policy

Replace ${orgId} with the Anypoint Platform Organization ID where the policy will be uploaded. Get your organization ID from Access Management > Organization. Click the name of your organization and copy the UUID from the browser address; for example, 2a4b93c3-7899-4ea7-9374-f787744d8784 from the URL.

Replace ${policyName} with the desired name for the Custom Policy.

Before finishing, Maven will ask you to set up:

  • policyDescription — a brief description of your policy
  • policyName — the identifier name of your policy

After running the command, the project’s directory will have a structure like the following:

my-custom-policy/

├── my-custom-policy.yaml

├── mule-artifact.json

├── pom.xml

└── src

   └── main

       └── mule

           └── template.xml

Those four files are the basics needed for a working policy.

This will create a Hello World Custom Policy in that folder.

Step 1. Import the code in Anypoint Studio workspace

Click on template.xml file -> configuration XML

This file will contain a Hello World application by default:

<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns=”http://www.mulesoft.org/schema/mule/core”

    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

    xmlns:http=”http://www.mulesoft.org/schema/mule/http”

    xmlns:http-policy=”http://www.mulesoft.org/schema/mule/http-policy”

    xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd

             http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd

             http://www.mulesoft.org/schema/mule/http-policy http://www.mulesoft.org/schema/mule/http-policy/current/mule-http-policy.xsd”>

  <http-policy:proxy name=”{{{policyId}}}-custom-policy”> (1)

      <http-policy:source> (2)

          <http-policy:execute-next/> (3)

           <set-payload value=”Hello World!”/>

      </http-policy:source>

  </http-policy:proxy>

</mule>

Change this XML to implement the use case.

NOTE: You can’t use the Message Flow section for drag and drop. For Custom policies, you must edit the configuration XML manually.

<?xml version=”1.0″ encoding=”UTF-8″?>

<mule xmlns:doc=”http://www.mulesoft.org/schema/mule/documentation”

     xmlns:http=”http://www.mulesoft.org/schema/mule/http”

     xmlns=”http://www.mulesoft.org/schema/mule/core”

     xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:http-policy=”http://www.mulesoft.org/schema/mule/http-policy” xsi:schemaLocation=”http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd

              http://www.mulesoft.org/schema/mule/http-policy http://www.mulesoft.org/schema/mule/http-policy/current/mule-http-policy.xsd

http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd”>

     <http:request-config name=”HTTP_Request_configuration” doc:name=”HTTP Request configuration” doc:id=”39f77353-1dfa-4afd-a9ea-1ae85c140e8e” >

         <http:request-connectionhost=”get-group-info.us-e2.cloudhub.io” />   

     </http:request-config>

   <http-policy:proxy name=”{{{policyId}}}-custom-policy”>

       <http-policy:source>

<http:requestmethod=”GET” doc:name=”Request” doc:id=”23fc25cd-795b-4073-ac2d-a4c56f21ee5a” config-ref=”HTTP_Request_configuration” path=”/api/department”>

              <http:headers ><![CDATA[#[output application/java

              —

              {

                   “department” : attributes.headers.department

              }]]]></http:headers>

         </http:request>

        <choice>

           <when expression=”#[payload == true]” >

             <http-policy:execute-next/>

          </when>

          <otherwise>

             <logger message=”Avoid Flow execution” />

              <set-payload value=”Invaild Department”doc:name=”Set Payload” doc:id=”eb18d93b-c4a2-490e-b014-7342efd6b2a1″ />

          </otherwise>

       </choice>     

       </http-policy:source>

   </http-policy:proxy>

</mule>

This policy will call http://get-group-info.us-e2.cloudhub.io/api/department to check if the provided header has “Department = IT” in the request. If the Department is IT, the request will be sent to the implementation URL.

Create a Proxy and add Custom Policy in the policy section, as shown below.

 

Proxy and Policy

Step 2. Packaging a Custom Policy

From the command line in your project’s folder, run the install phase > mvn clean install.

The packager will package your application and create a deployable jar file in the target directory within your project’s folder.

It will also verify that all the necessary files were provided for the packaging and that the information provided in the Mule Artifact and the policy yaml are valid.

Step 3: Deploying a policy created using the Maven Archetype

Run >mvn deploy to publish the policy to Exchange.

The custom policy is now available for you to apply to APIs that belong to the specified organization.

Step 4. Using Custom Policy in Exchange

Create Proxy and add Custom Policy in the policy section as shown below:

Using Custom Policy in exchange

Step 5: Testing the Custom Policy

Add the Custom Policy to your proxy and test it using Postman with the department header.

This should redirect to implementation URL.

Testing the custom policy

As a negative test, give any value other than IT in department or exclude the department from header section.

This should generate an error saying “Invaild Department.”

Generate an error saying “Invalid Department

Hopefully this is helpful.

— By Shivam Khandelwal