Tag Archives: API

Consuming, Developing & Managing API ; Azure API Management & App Service API services

Nuget WordPress REST API – Demo App

I’ve had a few requests to explain how to use the Nuget WordPress REST API beyond authentication.

In order to do this, I added a Demo App under source control.

The Nuget package source code is available at http://wordpressrestapi.codeplex.com/ and if you download the code, you’ll see there are 3 projects:

  • WordPressRestApi:  essentially the Nuget package
  • ApiClientTest:  Unit tests on the previous project
  • WordPressDemo:  The new Web App project

The demo project shows you a way to use the package.


Last year I posted an article on WordPress authentication, explaining how it works.  I would first read that article.

When you start the demo, it will take you into a sort of Authentication Wizard when you hit the web app root (e.g. http://localhost:58373/).

You need to go to https://developer.wordpress.com/apps/ and create yourself a WordPress App.  Give it a name & a description.  This is purely to run the demo on your laptop / desktop.  The redirect URL should be of the shape http://localhost:58373/SignIn but where you replaced 58373 by whatever port number the web app run on your laptop.

Once you created the app, at the bottom of the screen you should have access to the two elements of information you’ll need to run the demo.


On the demo web site you should be prompted to enter the client ID.


Usually we would have the Client ID and other app’s information in the web.config.  But to simplify the demo setup, I have the user keypunch them.

Once you’ve enter the client ID, click submit.  The app should give you a link to sign in WordPress.  Click it.

Your browser will have you navigate to https://public-api.wordpress.com/oauth2/authorize.  From there, WordPress will request your consent.  Click Approve.

FYI, the demo App only does read operations:  it won’t modify or delete anything.

From there you should be brought back to the redirect URL you configured.


You need to again enter the client ID.  You also need to enter the client secret.

You can the click on the Fetch Token button.  This will allow the web app to fetch a token for the WordPress App.

From there you should land on http://localhost:58373/DemoRead.

You can follow the authentication code from HomeController & SignInController classes (and models).

Read Operations

The class DemoReadController does the read operations.  Here we demo a query on posts & one on tags.

Everything flows from the WordPressClient.

We got rid of the tentative of building LINQ queries around WordPress and instead went for a thin interface on top of its REST API.

The surface of the REST API exposed is quite limited at this point:  posts and tags.

A particularity of the interface is the use of IAsyncEnumerable<T>, which is a custom interface allowing us to add a filter (where clause) and / or projection (select).  Those aren’t sent to the API, a la LINQ SQL, but they are at least processed as the objects are hydrated from the requests.  This interface also respects the async semantic hence allowing us to build more scalable application on top of it.


This demo app is by no mean a base for your WordPress applications.  Rather, it illustrates how to use the Nuget Package.

I hope this gives you a better idea on how to use it.

Refactoring Tags in WordPress Blog

imageI did refactor the tags of my blog this week end!

I display the tags (as a word cloud) on the right-hand side of my pages.  The tags grew organically since I started blogging in 2010.

As with many things that grow organically, it got out of hand with time.  First the technological space I covered in 2010 isn’t the same today but also, I did tend to add very specific tag (e.g. DocumentDB) and with time I ended up with over 60 tags.

With hundreds of blogs and 60 tags, the WordPress portal (I use WordPress.com for my blog) wasn’t ideal to start doing changes.

So I got my WordPress API .NET SDK out of the mothball Winking smile  I also updated my “portal” (deployed on Azure App Services) to that SDK.  This is probably one of the worst example of an ASP.NET MVC application but surely the ugliest site available out there.  It’s functional, that’s what I can say Winking smile

In case you want to do something similar on your blog, here is how I did it.


First I define target tags.  I did that by looking at the current list of tags but mostly I just gave myself a direction, i.e. the level of tags I wanted.

I then iterated on the following:

  • Look at the tags in WordPress portal, find targets for rename
  • Used the “Change Post Tags” functionality to change tags “en masse” on all the posts
  • Alternatively I used the “Edit Post Tags” functionality to edit the tags in Excel
  • Then use the “Clean up Tags” to remove tags that had no longer any posts associated to it

BTW, each of those functionalities tells you what they are going to do to your posts and ask for your consent before doing it.

After a couple of iterations I got the bulk of my tags cleaned up.

The last thing I did was to define the tags, i.e. add descriptions.  I did that within the WordPress portal.

Hopefully that should make my posts easier to search!

Securing REST API using Azure Active Directory

Scenario:  you have a web & mobile front-end, both using a REST API as a back-end.  You want to secure that back-end with authentication / authorization.  How do you do that in Azure?


There are obviously a bunch of ways to do that.  In this post, I’ll discuss the recommended approach:  using Azure Active Directory.  We’ll build an Hello World solution in .NET implementing it.

This is actually quite well documented in the Azure documentation so in this post I’ll just try to complete the documentation with practical points.

You can read about Azure API apps here and follow a good Getting started tutorial here.  This walks you through building a three tier app, exposes you to the powerful Swagger integration (you can read about Swagger in this post) and the configurations around Cross-Origin Resource Sharing (CORS).

You can then go about and read authentication / authorization of API apps here.

I will not cover API Management in this post but once you expose your API publically, i.e. not just to your own services, it’s a good idea to consider Azure API Management to manage it, if only to throttle usage to guarantee a good quality of service to everyone.

Overview of the solution

So we’re going to use Azure Active Directory (or Azure AD or AAD) as the identity provider for our solution.


Now keep in mind there are many variations on this architecture.  There could be a “Web API” within the Web app for AJAX calls.  There could be an Azure Mobile App API (used by the mobile device only), itself using the API app.  Many other variations.

Here we’ll focus on the architecture pictured in the diagram above.

Notice that the API app is accessed by two classes of identities:

  • Service Principal:  the Web app accesses the API as itself, not as the end-user
  • End-User Principal:  the mobile app accesses the API as the end-user

This creates an asymmetry within the API app.  For instance, authorization might be a bit funky since the API would trust the service principal to implement authorization rules on its end while it would need to implement it for the end-user.

This is one of the reason why some people might put another API between the mobile app & the back-end API.

In this post, I’ll focus on a Service Principal accessing an API app.

If you are unfamiliar with AAD applications, have a look at Azure Active Directory Application and if you’re unfamiliar with AAD Service Principals, read Using Azure Active Directory Service Principal.

Let’s build it!

Ok, let’s go and create a solution.  Let’s call it ApiAuthDemo.

Under that solution, let’s create a ASP.NET application.  I’m using VS 2015 so it might look a little different on other versions of the project.  I choose the ASP.NET Web Application template under the Cloud template folder.


I call the project AboutMeApi.  I then choose Azure API App sub-template.


I then create a straight Console App.  This will be the client accessing the API for the demo.


I call it AboutMeConsole.

So in the end, you should have the following structure in Visual Studio:


About Me API

Let’s flesh out the API.  And when I say flesh out, I mean let’s change 500 bytes of code.  This is a demo after all!

Under Models folder, create a class PersonaModel with the following code:

namespace AboutMeApi.Models
    public class PersonaModel
        public string Description { get; internal set; }
        public string Name { get; set; }
        public string[] Claims { get; internal set; }

Under the Controllers folder rename ValuesController by PersonaController.  This should hopefully rename the underlying class.  Let’s keep the following code:

using AboutMeApi.Models;
using System.Linq;
using System.Security.Claims;
using System.Web.Http;

namespace AboutMeApi.Controllers
    public class PersonaController : ApiController
        // GET api/values
        public PersonaModel Get()
            var identity = (ClaimsIdentity)User.Identity;
            var claims = from i in identity.Claims
                         select i.Type + " | " + i.Value;

            return new PersonaModel
                Description = "Description of the invoking user",
                Name = identity.Name,
                Claims = claims.ToArray()

As you can see, what this API does is take the current user information and return it to the caller.

Then under App_Start folder, in SwaggerConfig, uncomment the following:

// ***** Uncomment the following to enable the swagger UI *****
.EnableSwaggerUi(c =&gt;

Now we can start the web app to check out our API.  Start it with F5.  You should land on the root of your web site and get a Forbidden 403 error.  That’s because there is no content in the web site, it’s an API.

Go to the Swagger path:  http://localhost:18008/swagger/.  Actually, my web app is installed on port 18008, yours will be different as it is randomly assigned.

This gives you the beautiful Swagger UI.  You see the Persona API, expend it.  You’ll see the GET operation ; click it.  Then Try it out.  No parameters are required and you should have the following in return payload:

{ "Description": "Description of the invoking user", "Name": "", "Claims": [] }

That is because you aren’t authenticated so the current user is empty.  No problem, we’ll get there.

Configuring Service Principal in AAD

Before we build the client test console, we’ll need to be able to authenticate.

For that, we’ll create a Service Principal in AAD.  This will be the identity of the service calling our API ; in our case, the Console Application.

As explained in Azure Active Directory Application, an AAD application is a Service Principal which is the equivalent of a “Service User” in on premise AD, except it is a first class citizen.

Here I will refer you to the excellent article of Tom FitzMacken:  Create Active Directory application and service principal using portal to create your Service Principal in your AAD with the following properties:

Name Value
Name AboutMeConsoleClient
Sign-on URL https://console.Aboutme.com
App ID URI https://console.Aboutme.com

You’ll need to create a key and remember its value.  You should also copy the client ID of your Service principal.

Create API Application in AAD

This step could be done automatically when deploying your API app in Azure, but I like to see what’s going under the cover…  a little.

So let’s create another app with the following properties:

Name Value
Name AboutMeApi
Sign-on URL https://api.Aboutme.com
App ID URI https://api.Aboutme.com

We will change some of those properties when we deploy the API to Azure but it’s ok for now.

You do not need to create a key for that application as we will not login to AAD with it but use it only as an application for our Service Principal to log against.  You need to capture the client-ID of the app though.

Console App

Now we can build our console app.

First, let’s add a REST API client of the API we just created in the Console app.

Right-click on the Console project, select Add, follow the sub-menu to REST API Client…

You should see the following dialog.


Since Swagger defines the meta data of your API, it is possible to construct a client for it from that meta data.  This is what this tool does.

Select an existing swagger metadata file & click Browse.  Now you need to tell the system where the swagger file is.  If you go back to the Swagger web page, at the top of the screen you’ll see


So http://localhost:18008/swagger/docs/v1 is where your swagger metadata file is.  Again, the port number will likely be different on your PC.

Change the namespace for AboutMeConsole.AboutMeApi before hitting OK.

Now you can go in the Program file and paste the following code:

using AboutMeConsole.AboutMeApi;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace AboutMeConsole
    class Program
        static void Main(string[] args)

        private async static Task DoJobAsync()
            var authenticationResult = await AuthenticateAsync();
            var client = new AboutMeApiClient

            client.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(

            var persona = await client.Persona.GetAsync();

        private async static Task<AuthenticationResult> AuthenticateAsync()
            var authority = "https://login.microsoftonline.com/<your AAD name here>.onmicrosoft.com";
            //  Invoked App ID
            var resource = "<The client ID of AboutMeApi app>";
            var clientID = "<The client ID of AboutMeConsoleClient app>";
            var clientSecret = "<The secret key of AboutMeConsoleClient app>";
            var clientCredential = new ClientCredential(clientID, clientSecret);
            var context = new AuthenticationContext(authority, false);
            var authenticationResult = await context.AcquireTokenAsync(

            return authenticationResult;

You should have a few classes your system doesn’t recognize.  You need to import the NuGet package Microsoft.IdentityModel.Clients.ActiveDirectory to get those classes.

You can then go to the AuthenticateAsync method and replace the placeholder, e.g. <your AAD name here>, by the values you’ve collected.

Now let me explain a bit what the code does here.

First the style:  async.  This is a console app, so async is pretty useless since the main thread is always running, but I like to get everyone in the habit of using await / async for all their code.  So in the main, I do a call to an async method (DoJobAsync) and I wait (block) on it.  This is the only non-async code.  The rest you could copy paste in service code.

So, in DoJobAsync we first fetch a token from AAD, then we create an API client.  On that client we add the access token in the request headers.


We have the flow described above where the console app goes to AAD, authenticates itself as the console app, in the context of the API app (remember, authentication in AAD always is in the context of a target app).  It receives a bearer token that it passes to the API when invoking it.

Now if you try the console app, you’ll see that the persona object returned by the API is basically empty.  Why is that?

That’s because there is no code in the API app to crack open the token and find the identity of the caller.  We could add ADAL code there and that might be a sensible thing to do in a development environment, but I won’t cover this in this post.

Instead, I’ll leverage the authentication / authorization feature of Azure App Service.

Deploying the API in Azure

Let’s publish the API in Azure.  Put it under your favorite App Service Plan & Resource Group.

Try to call the API App name itself AboutMeApi.  But since it needs to be globally unique (being mapped to a DNS), you’ll likely need to append some numbers at the end.  I called mine AboutMeApi2016.

You can then go in the API app in the portal and select the Authentication / Authorization feature.


This feature is pretty handy.  It basically runs the authentication code outside of your app.  A gateway, in front of your app, intercept the bearer token cracks it open, does the cryptography to check out everything is valid and reemit http-headers your app can readily consume.  Isn’t that fantastic?  If not, what is, I’m asking you.

I definitely suggest you read the documentation around service authentication to understand the different options you have.

For us, let’s just switch the authentication to ON, leave the default to “Log in with Azure Active Directory”, then configure the AAD.  For that, select the Express Management mode and then select your app.  If you’re like me and have multiple AAD in your subscription and the AAD you’re using isn’t the default one, select Advanced.

In client ID, paste the client ID of the API app we created earlier.  In Issuer URL, you need to paste https://sts.windows.net/ and append the tenant id of your AAD.  To find that out, go to your AAD configuration, select “View Endpoints”


Then you should see the ID where I’ve put the orange box.


You can save your API App configuration in the portal.

Console App pointing to Azure App

Now let’s go back to our Console app and change the following code in DoJobAsync:

            var client = new AboutMeApiClient
                BaseUri = new Uri("https://aboutmeapi2016.azurewebsites.net")

Of course, you need to put your own unique URL there but…  and I can’t stress that enough, you need to put HTTPS in your url there.  If you don’t, the authorization feature is going to give you an unauthorized and if you’re lucky like me, you’ll need 3 hours to find out why.  Hint:  it is the letter ‘s’ missing at the end of ‘http’

Now, let’s run the console app.  You’ll see the persona object gets filled with information, including the list of claims given by AAD.

An interesting fact is that your Service Principal doesn’t have a name and this is why the name property is still blank.  Your application is identified by an app-id.

Token Cache

I went extremely quickly through the code but an interesting fact is that the object AuthenticationContext contains a property TokenCache which is a global cache in your app-domain.  This means that the next time you call it for an authentication, it won’t go to AAD to fetch a token.

This is gold for performance and scalability of course.

It is clever enough to figure out when the cached token are expiring and will then go again to AAD.


Ok, this wasn’t trivial I know.  Lots of GUIDs and configuration right-left & center.

But the important items are:

  • You can access an API App using a Service Principal ; this is what you’ll typically do for an API accessed as a “back-end” from another service
  • You can have different Service Principal accessing the same API and you could give different authorization to different ones ; authorization would be done in the code, either declaratively (Authorize attribute) or imperatively
  • Azure App Service can take care of the Authentication / Authorization for you

An issue you’ll have in your dev setup, i.e. your own PC while you develop your solution, is that you won’t have the App Service Authentication gateway in front of your service.

You could fix that in different ways.  You could ignore the authentication in dev, knowing it’s taken care of in production.  A bit risky, but you know you could have a flag making sure it’s there in production.  You could put ADAL code in your app and take care of the authentication yourself.  Or you could have a gateway in dev that essentially does the same thing than the one in Azure.  You simply don’t deploy it when you go to Azure.

Docker Containers on Windows Server

If you had any doubts about the increased pace in IT innovation, look at Docker Containers.  The project was open sources in March 2013 as a container technology for Linux and 1.5 years later, in Octobre 2014, Microsoft announced they were integrating that technology on Windows Server 2016!

That’s 1.5 years from toe in the water to major influence.  Impressive!


The first Windows Server Container Preview has been announced in August 2015 as part of the Technical Preview 3 of Windows Server.  The preview also comes with Visual Studio integration, in the form of Visual Studio tools for Docker.

Mark Russinovich also published a very good technical post about Docker containers on Windows:  what they are, what are the advantages & scenarios where they nicely apply to.

Basically, Docker Containers are standard packages to deploy solution on a host.  The main advantage of having Docker Containers are in the small footprint of the container which results in a higher density of applications on a given host and a very quick startup time, compare to a Virtual Machine where the entire OS must be loaded in memory and booted.

In Windows, hosts will come in two flavours:  Windows Server host & Hyper-V host.  The former will maximize resource utilization and container density on a host while the latter maximizes isolation.

At first the Hyper-V container sounds like it defies the purpose of having Docker Containers in the first place since they basically implement the container as an entire VM.  But if you think about it, on the long run it makes perfect sense.  The first version of Docker Container on Windows will likely have security holes in them.  Therefore if you have scenario with ‘hostile multi-tenants’, you’ll probably want to stick to Hyper-V.  But in time, the security of Docker on Windows will tighten and you’ll be able to move to normal containers as a configuration-change.

Service Fabric

We can imagine that once Windows Server 2016 roll out, we’ll see Docker Container appearing in Azure.  I wouldn’t be surprise to see them fuse with the App Services shortly after that.

They are also very likely to be part of the upcoming Azure Service Fabrik, Microsoft offering for rapidely building Micro Services.

Nuget WordPress REST API – Authentication

wordpress_logo[1]I use WordPress.com as my blog platform.  It hosts the WordPress CMS software and adds a few goodies.

I was curious about their API after noticing that my Blog App (Windows Live Writer) tended to create duplicate of pictures, leaving lots of unused assets in my Media library.  This really is a personal pet peeve since I’m still at less than %5 of my asset quota after 5 years.

There happens to be two APIs in WordPress.com.  The old XML RPC API, used by Windows Live Writer actually, and the new REST API.

The new API is what people would call a modern API:  its authentication is OAuth based, it is RESTful and has JSON payloads.

Surprisingly there didn’t seem to be any .NET client for it.  So I thought…  why not build one?

Enters WordPress REST API Nuget package.  So far, I’ve implemented the authentication, a get-user and a part of a search-post.

For the search-post, I took the not-so-easy-path of implementing a IQueryable<T> adapter in order to expose the Post API as a Linq interface.  I’ll write about that but for an heads-up:  not trivial, but it works and is convenient for the client.

I will release the source code soon, but for the moment you can definitely access the Nuget package.

You can trial the client on a site I’m assembling on https://wordpress-client.azurewebsites.net/Warning:  I do not do web-UI so the look-and-feel is non-existing Winking smile

Here I’ll give a quick how-to using the client.


WordPress.com has the concept of application.  If you’re steep in Claim based authentication, this is what is typically referred to as a relying party.  It is also equivalent to an application in Azure Active Directory.

You setup application in https://developer.wordpress.com/apps/.  The three key information you need in order to get a user to authorize your application to access WordPress.com are:

  1. Client ID:  provided by WordPress.com, the identifier of your application
  2. Client Secret:  also provided by WordPress.com, a secret it expects you to pass around
  3. Redirect URL:  provided by you, where WordPress will send the user back after consent is given

Here is the authorization flow:


# Description
1 The user clicks on a ‘sign in’ link from your web site.
2 Your web redirect the user’s browser to a WordPress.com site passing the client-ID of your application and the return-url you’ve configured.  The URL will be:https://public-api.wordpress.com/oauth2/authorize?client_id=&lt;your value>;redirect_uri=<your value>;response_type=code
3 Assuming the user consent for your application to use WordPress.com, the user’s browser is redirected to the Redirect URL you provided to WordPress.com.  In the query string, your application is given a code.  This code is temporary and unique to that transaction.
4 Your application can now contact directly (without the browser) the WordPress.com API to complete the transaction.  You POST a request tohttps://public-api.wordpress.com/oauth2/token

You need to post the code, the client-ID and other arguments.

5 The API returns you a token you can use for future requests.
6 For any future request to the API, you pass the token in the HTTP request.

Now, this is all encapsulated in the WordPress REST API Nuget package.  You still need to do a bit of work to orchestrate calls.

The link to the authorization page you need to redirect the end-user to can be given by:

static string WordPressClient.GetUserAuthorizeUrl(string appClientID, string returnUrl)

You pass the client-ID of your application and its return-url and the method returns you the URL you need to redirect to user to (step 2).

Then on the return-url page, you need to take the code query string parameter and call

static Task<WordpressClient> WordPressClient.GetTokenAsync(string clientID, string clientSecret, string redirectURL, string code)

This method is async.  All methods interacting with WordPress API are async.  The method returns you an instance of the WordPressClient class.  This is the gateway class for all APIs.

That was step 4 & 5 basically.

Rehydrating a WordPress Client between requests

That is all nice and well until your user comes back.  You do not want them to authorize your application at every request.

The typical solution is to persist the token in the user’s cookies so that at each request you can recreate a WordPressClient object.

For that you can access the token information in

TokenInfo WordPressClient.Token { get; }

When you want to recreate a WordPressClient, simply use its constructor:

WordPressClient(TokenInfo token)

Getting user information

Just as an example of how to use the API beyond authorization, let’s look at how to get information about the user.

Let’s say the variable client is a WordPressClient instance, then the following line of code

var user = await client.User.GetMeAsync();

gets you a bunch of information about your end-user profile on WordPress.com, such as their display name, the date the user join the site, their email, etc. .  This methods wraps the API operation https://developer.wordpress.com/docs/api/1.1/get/me/.


This was a quick run around this new WordPress REST API Nuget package I just created.  I’ll put it on Codeplex soon if you want to contribute.

SOA vs Mobile APIs

I recently read an article from Bill Appleton of Dream Factory with the provocative title SOA is not a Mobile Backend.

It raised quite a few good points that were in the back of my mind for more than a year.

Basically, what is the difference between SOA and API?

inclusion-229302_640[1]To an extent it is largely the domain of the buzzword department but as you think about it, it is more profound.

SOA really is an Enterprise Creature.  It’s a system integration strategy (despite what SOA purist will tell you).  As Bill mentions in his article, SOA also typically comes with its heavy Enterprise artillery:  Enterprise Service Bus, XML Message Translation, Service Locator, etc.  .  But it also comes with a set of useful practices:  domain knowledge, reusable services, etc.  .

API is an internet beast.  How do you interact with a service on the cloud?  You talk to its API.  API are typically simpler in terms of protocols:  HTTP, REST, JSON, simple messages, etc.  .  They are also messy:  is an API about manipulating a specific entity or doing a consisting set of functionalities?

To me, they spawn from the same principles, i.e. standard interface to exchange information / commands in a loosely couple way between remote components.  SOA is the Enterprise & earlier result of those principles.  API is the internet / mobile later result.

SOA was tried by some big enterprises, forged by comity with expensive consultants and executives trying to solve the next 10 years problem.

Integration_logo[1]API was put forward by a myriad of small companies and consumed by even more entities.  They figured out the simplest way to expose / consume services quickly and learned from each other.  In a few years a few set of practices were observed and documented and standards are even emerging.

Bill, in his article, contrasts the approaches in a way that reminds me of the old SOA debate of top-bottom vs bottom-top approaches, that is, do you discover your services by laying down your business processes and drilling down discover a need for services or by looking at your applications and which services they expose and hope that one day you can reuse them?

There is a lot of that in the issues brought by Bill around APIs.  Like in SOA if you just spawn new APIs ‘On demand’, you’ll end up with a weird mosaic with overlapping concepts or functionalities.  I agree that practices developed from SOA can definitely helped.  Service Taxonomy, for instance, forces you to think of how your services will align and where their boundaries will be drawn before you start.

But for an organization, I believe it is nearly a forced therapy to implement one or two APIs, experiment them in full operation before you can start having serious discussion around other SOA aspects.  Once you’ve tried it, you can have a much more informed discussion about what changes and at which in a service (while discussing versioning), what type of security rules make sense and a bunch of other aspects.

Otherwise you fall victim of the good old analysis paralysis and will host meetings after meetings for deciding about something because everyone has a different a priori perspective on it.


So my suggestion is yes, API are a little messier, but experimenting with them, even if you end up with a lot of rework, will bring much value to your organization.  So go, and create simple API, expose them and operate them!