Search code examples
azure-api-managementapim

how to check null header values in apim and throw error response back


I want to check if the specific header contains null values if the value is null then throw error bad request how to achive this functionality in apim

<validate-headers specified-header-action="ignore | prevent | detect" unspecified-header-action="ignore | prevent | detect" errors-variable-name="variable name">
    <header name="header name" action="ignore | prevent | detect" />
</validate-headers>

any example I have seen above code in apim documentation but not sure how to check null values


Solution

  • I did the same and my Scenario was validate the JWT-Token Header token and response back if JWT is missing. I did below code and for me it's working.

    <set-variable name="JWTToken" value="@(context.Request.Headers.GetValueOrDefault("Authorization"))" />
    <choose>
        <when condition="@(context.Variables.GetValueOrDefault<string>("JWTToken") == null || !context.Variables.GetValueOrDefault<string>("JWTToken").Contains("Bearer "))">
            <return-response response-variable-name="cartErrorResponse">
                <set-status code="400" reason="reason" />
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-body>{
                      "error": {
                            "code": "APIMC002",
                             "type": "",
                             "text": "Token is missing in header"
                       }
                       }</set-body>
            </return-response>
        </when>
    </choose>