How to combine the REST API from Azure API Management with LINQ and a Subscription key to get the UserId

In Azure API Management, developers are the users of the APIs that you expose using API Management. In order to make calls to an API, developers must first subscribe to a product that gives them access to it. Developers can subscribe to products in the Developer portal and get a primary and secondary subscription key for the product. This key is used when making calls into the product's APIs.

 
APIM Developer portal - User profile
 
This is a great way to add security on top of your Web API and a while ago I wrote a blog post about using the API Management user subscription key in the back-end API App.
Having access to the subscription key in the back-end Web API App is great but there is also a problem with storing the subscription key because for each Product you get a separate key and also you can regenerate a key so if you would have the unique id of the developer that would be even more convenient!
 

The following steps describe how to use the REST API from Azure API Management to get all the subscriptions and then use a LINQ query on the subscriptions to get the corresponding user id.

  • Enable access to the REST API     
  • Read the subscription key value from the request header
  • Create a Repository class to get the UserId

    

      Enable access to the REST API

      Access to the API Management REST API must be granted before calls can be successfully made. To enable access, sign into the Azure Portal, navigate to your API Management service instance, and click on Management API in the Security section of the left navigation menu.
      Azure Portal - API Management REST API
       
      To enable API Management ensure that the REST API checkbox is checked.
      Azure Portal - Enable API Management REST API
       
      Each request to the API Management REST API must be accompanied by an Authorization header containing a valid shared access token.
      Under the Access token box click on the Generate button to generate it from within the Azure portal.
      Azure Portal - Generate Access token

       

      Read the subscription key value from the request header

      Modify the methods in the Web API 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.

      IEnumerable<string> headerValues;
      string subscriptionKey = null;

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

       

      Create a Repository class to get the UserId

      In the Web API Controller class call the Repository class to get the user id with the "Ocp-Apim-Subscription-Key" as a input parameter. In the Repository call the GET Subscriptions operation from the API Management REST API to return a collection of all subscriptions. Then you can use a LINQ query on the result subscriptions list to get the subscription from the user.

      public class ApimRepository
      {

          string ApimRestHost = ConfigurationManager.AppSettings["ApimRestHost"];
          string ApimRestAuthHeader = ConfigurationManager.AppSettings
          ["ApimRestAuthHeader"];
          string ApimRestApiVersion = "2014-02-14-preview";      


          public async Task<string> GetUserIdByToken(string primaryKey)
          {

              string userId = null;

              using (var client = new HttpClient())
              {

                  client.BaseAddress = new Uri(ApimRestHost);
                   client.DefaultRequestHeaders.Add("Authorization",
         
                                               ApimRestAuthHeader);

                  // Get all the subscriptions from API Management
                  HttpResponseMessage response = await client.GetAsync
                  ("/subscriptions?api-version=" + ApimRestApiVersion);
                  if (response.IsSuccessStatusCode)
                   {
                      HttpContent cont = response.Content;        

                      string jsonContent = cont.ReadAsStringAsync().Result;
                      Subscriptions list = JsonConvert.DeserializeObject
                                           <Subscriptions>(jsonContent);

                      // Get the specific subscription from the list with LINQ
                      Subscription s = list.value.Where(a => a.primaryKey == 
                                                  primaryKey).FirstOrDefault();

                      if (s != null)
                      {
                           // Remove "/users/" from id
                          userId = s.userId.Substring(7);
                      }
                  }
               }

              return userId;
          }
      }

       

      Wrap Up

      The REST Web API from Azure API Management makes it very easy to get information on selected entities, such as users, groups, products, and subscriptions. Combining it with LINQ adds even more functionality because now you have extra properties where you can filter on!

      You can download the code here:
      Console-App-that-combines-the-Azure-API-Management-REST-API-with-LINQ

      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