Created
December 20, 2017 17:18
-
-
Save ahelland/f5b12bf68a798b97d40d823a19a00853 to your computer and use it in GitHub Desktop.
Azure API Management Policy for validating jwt and rewriting authorization header to use a SAS Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<inbound> | |
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized"> | |
<openid-config url="https://login.microsoftonline.com/common/.well-known/openid-configuration" /> | |
<audiences> | |
<audience>https://management.core.windows.net/</audience> | |
</audiences> | |
<required-claims /> | |
</validate-jwt> | |
<set-header name="Authorization" exists-action="override"> | |
<value>@{ | |
var resourceUri = "contoso.servicebus.windows.net"; | |
var keyName = "RootManageSharedAccessKey"; | |
var key = "randomKey"; | |
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1); | |
var week = 60 * 60 * 24 * 7; | |
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week); | |
string stringToSign = Uri.EscapeDataString(resourceUri) + "\n" + expiry; | |
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)); | |
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign))); | |
var sasToken = String.Format("SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", Uri.EscapeDataString(resourceUri), Uri.EscapeDataString(signature), expiry, keyName); | |
return sasToken; | |
} | |
</value> | |
<!-- for multiple headers with the same name add additional value elements --> | |
</set-header> | |
<set-backend-service id="apim-generated-policy" base-url="https://contoso.servicebus.windows.net" /> | |
</inbound> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment