Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

Using the acquired token to call a protected Web API

Jean-Marc Prieur edited this page Feb 13, 2018 · 2 revisions

Using the token

Getting a token is not a goal per se. It's a necessary step to call a protected API. The token needs then to be used to access a Web API. The way to do it, is by setting the Authorization header to be "Bearer", followed by a space, followed by the access token.

Using the access token to call a protected Web API

Note that the code below shows how to call directly the web API with an HttpClient. You can also use libraries which will only require the access token (DocumentDb for instance) and will take care of the headers details. In practice the code might change depending on the libraries you want to call

// Using the token
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", result.CreateAuthorizationHeader());
HttpResponseMessage r = await client.GetAsync(resourceUrl);

The following are, by the way, equivalent:

client.DefaultRequestHeaders.Add("Authorization", result.CreateAuthorizationHeader());

or

string accessToken = result.AccessToken;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

or

string accessToken = result.AccessToken;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

Example: using the access token to call the Microsoft Graph using the .NET API

One of the Web API you might want to call is the Microsoft Graph. Although you can always do it by calling the Rest call yourself with an HttpClient, you might want to use the Microsoft Graph .NET API (See https://www.nuget.org/packages/Microsoft.Graph) There are many samples on how to do that with MSAL.NET (See the samples in the GitHub MicrosoftGraph organization containing the string csharp). This is also possible with ADAL.NET. Here is for instance some minimal code doing so:

 public class Config
 {
  // STS
  public string Authority { get; set; } = "https://login.microsoftonline.com/microsoft.com";

  // Resource to access
  public string Resource { get; set; } = "https://graph.microsoft.com";

  // Application
  public string ClientID { get; set; } = "b391c547-acf3-4bb1-b4d7-f8df005a37df";
  public string ReturnUri { get; set; } = "https://MyTutorial";
 }

 class Program
 {
  static void Main(string[] args)
  {
   Config config = new Config();
   QueryGraph(config).Wait();
  }

  private static async Task QueryGraph(Config config)
  {
   AdalNaiveAuthenticationProvider adalNaiveAuthenticationProvider = new AdalNaiveAuthenticationProvider(config);
   GraphServiceClient graph = new GraphServiceClient(adalNaiveAuthenticationProvider);
   User me = await graph.Me.Request().GetAsync();
   . . .
  }

And here is authentication code, leveraging ADAL.NET:

 public class AdalNaiveAuthenticationProvider : IAuthenticationProvider
 {
  public AdalNaiveAuthenticationProvider(Config config)
  {
   this.config = config;
   authenticationContext = new AuthenticationContext(config.Authority);

  }

  public async Task AuthenticateRequestAsync(HttpRequestMessage request)
  {
   AuthenticationResult result;
   // oversimplified code
   result = await authenticationContext.AcquireTokenAsync(config.Resource, config.ClientID, 
                                                          new Uri(config.ReturnUri), 
                                                          new PlatformParameters(PromptBehavior.Auto));
   request.Headers.Add("Authorization", result.CreateAuthorizationHeader());
  }
  AuthenticationContext authenticationContext;
  Config config;
 }

Note that this code authentication code is oversimplified (it systematically has the user sign-in, does not benefit from a cache, and does not do any error handling). We'll see in more details how to write enterprise ready code in other topics

Clone this wiki locally