Azure / api-management-policy-snippets

Re-usable examples of Azure API Management policies
MIT License
345 stars 157 forks source link

Get thumbprint from certificate retrieved from Keyvault #47

Open andrewwiebe opened 4 years ago

andrewwiebe commented 4 years ago

I am trying to use the policy from the example, Look up Key Vault certificate using Managed Service Identity and call backend.

I am able to get the certificate from the key vault and use if to authenticate to my back end as a client cert. but i am also trying to secure the inbound call on the front end by validating that the caller is sending the same cert.

Using the policy below I am able to retrieve the cert from the keyvault, get the Base64 value out of the cert response. The last step I am missing is how to pull the thumbprint out of that Base64 cert to validate against in the incoming cert thumbprint from context.Request.Certificate.Thumbprint.

The comparison i am struggling with is

<when condition="@(Convert.FromBase64String((string)context.Variables["keyVaultCertBase64"]) != context.Request.Certificate)">

Full Inbound Policy

<inbound>  
        <base />
        <send-request mode="new" response-variable-name="keyVaultCertResponse" timeout="20" ignore-error="false">
            <set-url>https://MYKEYVAULTNAME.vault.azure.net/secrets/CLIENTCERTTEST/?api-version=2016-10-01</set-url>
            <set-method>GET</set-method>
            <authentication-managed-identity resource="https://vault.azure.net" />
        </send-request>
        <set-variable name="keyVaultCertBase64" value="@(((IResponse)context.Variables["keyVaultCertResponse"]).Body.As<JObject>()["value"].ToString())" />
        <choose>
            <when condition="@(context.Request.Certificate == null)">
                <return-response>
                    <set-status code="403" reason="No Client Certificate Provided to APIM" />
                </return-response>
            </when>
            <when condition="@(Convert.FromBase64String((string)context.Variables["keyVaultCertBase64"]) != context.Request.Certificate)">
                <return-response>
                    <set-status code="403" reason="Client Certificate Presented to APIM is incorrect" />
                </return-response>
            </when>
        </choose>
        <authentication-certificate body="@(Convert.FromBase64String((string)context.Variables["keyVaultCertBase64"]))" />
    </inbound>
tomkerkhove commented 4 years ago

Feel free to do a PR so it can be added!