Muokkaa

Jaa


A web API that calls web APIs: Call an API

After you have a token, you can call a protected web API. You usually call the downstream APIs from the controller or pages of your web API.

Controller code

When you use Microsoft.Identity.Web, you have three usage scenarios:

Option 1: Call Microsoft Graph with the SDK

In this scenario, you've added the Microsoft.Identity.Web.GraphServiceClient NuGet package and added .AddMicrosoftGraph() in Startup.cs as specified in Code configuration, and you can directly inject the GraphServiceClient in your controller or page constructor for use in the actions. The following example Razor page displays the photo of the signed-in user.

 [Authorize]
 [AuthorizeForScopes(Scopes = new[] { "user.read" })]
 public class IndexModel : PageModel
 {
     private readonly GraphServiceClient _graphServiceClient;

     public IndexModel(GraphServiceClient graphServiceClient)
     {
         _graphServiceClient = graphServiceClient;
     }

     public async Task OnGet()
     {
         var user = await _graphServiceClient.Me.GetAsync();
         try
         {
             using (var photoStream = await _graphServiceClient.Me.Photo.Content.GetAsync())
             {
                 byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                 ViewData["photo"] = Convert.ToBase64String(photoByte);
             }
             ViewData["name"] = user.DisplayName;
         }
         catch (Exception)
         {
             ViewData["photo"] = null;
         }
     }
 }

Option 2: Call a downstream web API with the helper class

In this scenario, you've added .AddDownstreamApi() in Startup.cs as specified in Code configuration, and you can directly inject an IDownstreamWebApi service in your controller or page constructor and use it in the actions:

 [Authorize]
 [AuthorizeForScopes(ScopeKeySection = "TodoList:Scopes")]
 public class TodoListController : Controller
 {
     private IDownstreamWebApi _downstreamWebApi;
     private const string ServiceName = "TodoList";

     public TodoListController(IDownstreamWebApi downstreamWebApi)
     {
         _downstreamWebApi = downstreamWebApi;
     }

     public async Task<ActionResult> Details(int id)
     {
         var value = await _downstreamWebApi.CallApiForUserAsync(
             ServiceName,
             options =>
             {
                 options.RelativePath = $"me";
             });
         return View(value);
     }

The CallApiForUserAsync method also has strongly typed generic overrides that enable you to directly receive an object. For example, the following method received a Todo instance, which is a strongly typed representation of the JSON returned by the web API.

 // GET: TodoList/Details/5
 public async Task<ActionResult> Details(int id)
 {
     var value = await _downstreamWebApi.CallApiForUserAsync<object, Todo>(
         ServiceName,
         null,
         options =>
         {
             options.HttpMethod = HttpMethod.Get;
             options.RelativePath = $"api/todolist/{id}";
         });
     return View(value);
 }

Option 3: Call a downstream web API without the helper class

If you've decided to get an authorization header using the IAuthorizationHeaderProvider interface, the following code continues the example code shown in A web API that calls web APIs: Acquire a token for the app. The code is called in the actions of the API controllers. It calls a downstream API named todolist.

After you've acquired the token, use it as a bearer token to call the downstream API.

private async Task CallTodoListService(string accessToken)
{
  // After the token has been returned by Microsoft.Identity.Web, add it to the HTTP authorization header before making the call to access the todolist service.
  authorizationHeader = await authorizationHeaderProvider.GetAuthorizationHeaderForUserAsync(scopes);
  _httpClient.DefaultRequestHeaders["Authorization"] = authorizationHeader;

  // Call the todolist service.
  HttpResponseMessage response = await _httpClient.GetAsync(TodoListBaseAddress + "/api/todolist");
  // ...
}

Next steps

  • Learn more by building an ASP.NET Core web app that signs in users in the following multi-part tutorial series

  • Explore Microsoft identity platform web API samples