Azure, Usage of CDN API to Load and Purge content

c"Hello World"!

Azure CDN is a great and powerful feature that is straightforward to setup and configure, but the management of the CDN content can be performed only via the Azure Portal or directly invoking the CDN APIs. There are no CDN PowerShell cmdlets at the moment.

The API to load or purge specific content is quite simple:

https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/Profiles/{profileName}/endpoints/{endpointName}/{actionName}?api-version=2015-06-01

You just need to replace the placeholders in the URI with your values and set actionName to purge or load.  In the request body you need to specify the elements that will be affected by the action.

For example, this simple JSON tells the CDN to purge or load two files located at the root level:

                { "ContentPaths": [ "/pic1.jpg", "/pic2.jpg" ] }

At the very same way If you want to purge all the content in one step you can use the "/*" wildcard (note: this wildcard does not work for the load action).

The format of this API is quite simple but as you can imagine it is protected and can be called only from authorized users, so you need to prove your identity before to use it.

This API is part of the new Azure Resource Manager namespace, so as every other Azure REST API in this namespace it must be authorized with a JWT token from Azure AD.

As per documentation, this token must be specified as http header:

                Authorization: Bearer XXXXXXXXXYYYYZZZZZZ…==

So the first step is to retrieve the JWT token from your Azure directory. But before to be able to query Azure AD for the JTW token you have to do some preliminary steps (using the classic portal):

  1. Add a user to your Azure AD and set this user as Co-Admin to have execution permissions (or, better, use the role based approach in new portal)
  2. Create a native client application in Azure AD and:
    1. Take note of the Client ID for this application (i.e.:  "XXXXXX-ZZZZZZZ-YYYY-OOOOO-UUUUUUUUUU")
    2. Grant the permissions to Windows Azure Service Management API

This Azure AD application can then be used to obtain the token.

To best way to login into Azure AD is using the classes provided by the Microsoft.IdentityModel.Clients.ActiveDirectory nuget package:

  public static string GetAToken()
 {
   //authentication parameters
   string clientID = "XXXXXX-ZZZZZZZ-YYYY-OOOOO-UUUUUUUUUU"; 
   string username = "youraccount@yourdirectory.com";
   string password = "XXXXX";
   string directoryName = "yourdirectoryname.com";
   var authenticationContext = new AuthenticationContext("https://login.windows.net/" + directoryName);
   var credential = new UserCredential(username, password);
   var result = authenticationContext.AcquireToken("https://management.core.windows.net/", clientID, credential);
 
   if (result == null)
   {
  throw new InvalidOperationException("Failed to obtain the JWT token");
   }
   string token = result.AccessToken;
   return token;
 }

 

Once you have the token (that is basically a base64 string) you can attach it as an HTTP header and call the CDN API:

 WebClient client = new WebClient();
//authentication using the Azure AD application
var token = GetAToken();
client.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
//Format the BODY as JSON array
dynamic content = new { ContentPaths = new List<string>() { "/pic1.jpg", "/pic2.jpg" } };
var body = JsonConvert.SerializeObject(content);
//POST to API
var result = client.UploadString(URI, body);

 

If the operation completes successfully the status code will be 202, and the response headers will contain some azure related fields like the GUID of the operation. In case of errors the WebClient instance throws an exception.

Remember that this API is async so it returns almost immediately but the requested operation might take some time to complete on the CDN side.

Last, if you want to check if a CDN resource has been properly loaded/purged you can inspect the response header of the CDN url:

        Invoke-WebRequest -Uri https://mycdnendpoint.azureedge.net/pic1.jpg

        StatusCode        : 200

        StatusDescription : OK

        Content           : {80, 75, 3, 4...}

        RawContent        : HTTP/1.1 200 OK

                    X-Cache: HIT

                    x-ms-blob-type: BlockBlob

                    x-ms-lease-status: unlocked

                    x-ms-request-id: 812ae27b-0001-001a-1fdf-513dc7000000

                    x-ms-version: 2009-09-19

                    Accept-Ranges: bytes

                    Content-Le…

The header "X-Cache: HIT" means the resource has been read from the CDN cache, if this header is not present then the resource has been read from the original repository.