0
votes

My project using api mangement service as azure APIM.I am trying to validate the claim using APIM Product policy .If the claim is not valid return an error otherwise allow to access the end point.Following is my policy

   <policies> <inbound> <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    ------------
    ------------ 
</validate-jwt> 
<choose> 
<when condition="@(context.Request.Method != "POST" && ((Jwt)context.Request.Headers["Authorization"].Claims["role"]!= "Owner") && (string)context.Api.Path =="/api/user"> 
<return-response>
 <set-status code="403" reason="Forbidden" />
</return-response>
 </when> </choose>
<base /> 


 </inbound> <backend> <base /> </backend> <outbound> <base /> </outbound> <on-error> <base /> </policies>

But even if the role is not owner user can able to access the /api/user path how to validate correctly ?

JWT calims are
 "userrole": "[Owner,Admin]",
 "email": "[email protected]"
1
If it helps you, please accept it as answer.Joey Cai

1 Answers

1
votes

This example shows how to use the Validate JWT policy to authorize access to operations based on token claims value.

<validate-jwt header-name="Authorization" require-scheme="Bearer" output-token-variable-name="jwt">
    <issuer-signing-keys>
        <key>{{jwt-signing-key}}</key> <!-- signing key is stored in a named value -->
    </issuer-signing-keys>
    <audiences>
        <audience>@(context.Request.OriginalUrl.Host)</audience>
    </audiences>
    <issuers>
        <issuer>contoso.com</issuer>
    </issuers>
    <required-claims>
        <claim name="userrole" match="any">
            <value>Owner</value>
            <value>Admin</value>
        </claim>
    </required-claims>
</validate-jwt>
<choose>
    <when condition="@(context.Request.Method == "POST" && !((Jwt)context.Variables["jwt"]).Claims["group"].Contains("Owner"))">
        <return-response>
            <set-status code="403" reason="Forbidden" />
        </return-response>
    </when>
</choose>

For more details, you could refer to this article.