Question

Difficulty: Very hardDefine API Management Policies

You are configuring an inbound policy in Azure API Management (APIM) to extract user information from a custom HTTP header named `X-Auth-Token`, which contains a raw JSON Web Token (JWT). The policy must extract the first value of the `email` claim from the token and forward it to the backend service inside a new request header named `X-User-Email`. If the claim is not present, it should default to an empty string.

Complete the XML policy definition below by filling in the correct C# extension method and JWT property name in the blanks.

Answer:xml
<policies>
<inbound>
<base />
<set-header name="X-User-Email" exists-action="override">
<value>@(context.Request.Headers.GetValueOrDefault("X-Auth-Token", "").【AsJwt】()?.【Claims】.GetValueOrDefault("email")?[0] ?? "")</value>
</set-header>
</inbound>
</policies>

Answer

To extract the `email` claim from the raw JWT in the `X-Auth-Token` header, you must convert the string token using the `AsJwt` extension method, and then access its `Claims` property. The correct values for the blanks are `AsJwt` for the first blank and `Claims` for the second blank.
The correct configuration uses the `AsJwt` extension method on the token string to parse the JWT into a helper object. It then accesses the `Claims` property of this object, which returns a dictionary containing all the claims in the token. Using `GetValueOrDefault("email")?[0]` retrieves the first value of the `email` claim in a null-safe manner.

Step-by-Step Solution

1
Identify the string extension method in Azure API Management policy expressions that parses a raw JWT string.
The `AsJwt()` extension method is used to parse a JWT string and return a C# object of type `Jwt`.
Before you can inspect claims or other properties of a JWT in a policy expression, you must convert the string representation of the token into a helper object.
2
Identify the property of the `Jwt` class that exposes the claims dictionary.
The `Claims` property exposes the token's claims as a read-only dictionary (`IReadOnlyDictionary<string, string[]>`).
Custom claims, such as `email`, are stored in the claims dictionary and can be retrieved using standard dictionary lookup methods.
3
Use safe navigation to access the first element of the claim array and provide a fallback.
The expression uses `GetValueOrDefault("email")?[0] ?? ""` to safely retrieve the first email address or fall back to an empty string.
This prevents runtime exceptions if the claim is missing or if the array is empty.

Key Concept

Azure API Management policy expressions allow the use of C# code to perform dynamic request transformation. The `AsJwt()` extension method and `Claims` property of the `Jwt` class enable inspection and extraction of specific JWT claims directly within policies.
Rate this question