Using API Management user subscription keys in the back-end API App

Azure API Management gives you the tools you need for end-to-end API management like provisioning user roles, creating usage plans and quotas, applying policies for transforming payloads and for example setting up throttling.
So it’s a great way to add extra security on top of a web API. The API Management gateway in Azure and the back-end service even don’t have to be connected to each other. But what if you want to know in the back-end web API which user from API Management calls the API? This may be necessary for example if you need to implement logic that a specific user can only see its own data.

When a developer in API Management subscribes to a product he is granted a primary and secondary subscription key for the product. This key is used when making calls into the product's APIs. Luckily its also forwarded to the the underlying web API and therefore can be used for your own purposes.

API Management Developer Portal - User Profile

 

 

 

 

 

 

The following steps are necessary to use the API Management subscription key in the underlying API.

  • Create code in API App to store the subscription key
  • Publish the API App to Azure
  • Import the API App in Azure API Management
  • Call the API App from the API Management Developer Portal

 

Create code in API App to store subscription key

To show how to store the developer subscription key I’m going to modify the OrdersAPI sample that I have created in my previous blog post.

Add the SubscriptionKey property to the order object that is used on the server. this object has also meta data properties like OrderStatus and CreationDate.
public class ServerOrder
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
    public Customer customer { get; set; }
    public Item item { get; set; }
    public string OrderStatus { get; set; }
    public DateTime ModifiedDate { get; set; }
    public DateTime CreationDate { get; set; }
    public string SubscriptionKey { get; set; }         
}
 
Modify the DAL class to create the ServerOrder object, give the SubscriptionKey property a value and store it in DocumentDB.
public async Task<string> CreateOrder(ClientOrder order, string subscriptionKey)
{
    string id = null;

    //Create a server order with extra properties
    ServerOrder s = new ServerOrder();

    s.customer = order.customer;
    s.item = order.item;

    //Add meta data to the order
    s.OrderStatus = "in progress";
    s.CreationDate = DateTime.UtcNow;
    s.SubscriptionKey = subscriptionKey;

    //Get a Document client
    using (client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
    {

        string pathLink = string.Format("dbs/{0}/colls/{1}", databaseId, collectionId);
        
        ResourceResponse<Document> doc = await client.CreateDocumentAsync(pathLink, s);

        //Return the created id
        id = doc.Resource.Id;
    }
    return id;
}
 
Modify the methods in the API App Controller class to read the "Ocp-Apim-Subscription-Key" value from the request header. Return a HTTP 401 Unauthorized error if the value is not present.
public async Task<IHttpActionResult> Post([FromBody]ClientOrder order)
{
    OrderResult result = new OrderResult();

    IEnumerable<string> headerValues;
    string subscriptionKey = null;

    if (Request.Headers.TryGetValues("Ocp-Apim-Subscription-Key", out headerValues))
    {
        subscriptionKey = headerValues.FirstOrDefault();
    }

    if (subscriptionKey != null)
    {
        OrderManager mgr = new OrderManager();
        string id = await mgr.CreateOrder(order, subscriptionKey);

        if (id != null)
        {
            result.Id = id;
        }

        // Return a HTTP 200 with the created id
        return Ok(result);
    }
    else
    {
        // Return HTTP 401 Unauthorized 
        throw new HttpResponseException(HttpStatusCode.Unauthorized);
    }
}
 

 

Publish the API App to Azure

This blog port does not describe how to publish an API App to Azure but only focuses on the specific steps that are necessary to make this sample work. See Get started with API Apps for how to create and publish an API App.

In your browser address bar go to the URL of the API app and add swagger to the end of the line. Copy the URL in the Swagger field. This is the default URL used by Swashbuckle to return Swagger JSON metadata for the API.

API App - Swagger UI page

 

 

 

 

 

 

 

 

 

Import the API App in Azure API Management

This blog port does not describe how to set up API Management in Azure but only focuses on the specific steps that are necessary to make this sample work. See Manage your first API in Azure API Management for how to set up API Management in Azure.

The generated Swagger metadata from the previous step makes it easy to import the API App in Azure. Go to the API Management Dashboard and click on “Import API”.
API Management Dashboard - Import API
 
Use the URL with the Swagger metadata from the API App to import the API App in API Management.
API Management Dashboard - Import API Details
 

 

Call the API App from API Management Developer Portal

The API App can be called directly from the Developer Portal, which provides a convenient way to view and test the operations of the API.

Enter the Request Body and click on the Send button. The "Ocp-Apim-Subscription-Key" key is automatically added to the header of the request.
API Management Developer Portal - Create Request
 
After the POST operation is invoked, the developer portal displays a HTTP 200 status with the created id if the body and the header of the request is correct.
API Management Developer Portal - HTTP Response
 

Check in the Azure Portal with the Document Explorer if the order and the SubscriptionKey really is stored in DocumentDB. 

Azure DocumentDB
 

 

Wrap Up

The API Management Subscription key which provides access to an API can also easily be used in the underlying web API. This can be very useful you want to know in the back-end API which user from API Management calls the API.

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

Tomasso Groenendijk lives in Netherlands and is a senior integration consultant at Motion10. He has over 15 years’ experience in software development and software design. Tomasso is specialized in application integration with a strong interest in the Windows Azure cloud platform. In 2014, 2015 and 2016 Tomasso was awarded with the Microsoft Azure MVP award. He is an active contributor to the integration community through his work on his blog, MSDN samples, TechNet Wiki and also speaking on events.

 
 
 
MVP profile Tomasso Groenendijk
 
 
Sentinet Product Specialist
 
 
BizTalk360 Product Specialist

Month List