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.
Cevap: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>
<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>
Cevap
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.
Adım Adım Çözüm
Anahtar Kavram
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.