웹 API를 호출하는 웹 API: API 호출
토큰이 있으면 보호된 웹 API를 호출할 수 있습니다. 일반적으로 웹 API의 컨트롤러나 페이지에서 다운스트림 API를 호출합니다.
컨트롤러 코드
Microsoft.Identity.Web을 사용하면 세 가지 사용 시나리오가 제공됩니다.
- 옵션 1: SDK를 사용하여 Microsoft Graph 호출
- 옵션 2: helper 클래스를 사용하여 다운스트림 웹 API 호출
- 옵션 3: 도우미 클래스 없이 다운스트림 웹 API 호출
옵션 1: SDK를 사용하여 Microsoft Graph 호출
이 시나리오에서는 코드 구성에 지정된 대로 Microsoft.Identity.Web.GraphServiceClient NuGet 패키지를 추가하고 Startup.cs에 .AddMicrosoftGraph()
를 추가했으며, 작업에 사용하기 위해 컨트롤러나 페이지 생성자에 GraphServiceClient
를 직접 삽입할 수 있습니다. 다음 Razor 페이지 예에서는 로그인한 사용자의 사진이 표시됩니다.
[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;
}
}
}
옵션 2: helper 클래스를 사용하여 다운스트림 웹 API 호출
이 시나리오에서는 코드 구성에 지정된 대로 Startup.cs에 .AddDownstreamApi()
를 추가했으며 컨트롤러 또는 페이지 생성자에 IDownstreamWebApi
서비스를 직접 삽입하고 작업에 사용할 수 있습니다.
[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);
}
CallApiForUserAsync
메서드에는 직접 개체를 받을 수 있도록 하는 강력한 형식의 일반적인 재정의가 있습니다. 예를 들어 다음 메서드는 웹 API에서 반환된 JSON의 강력한 형식의 표현인 Todo
인스턴스를 수신합니다.
// 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);
}
옵션 3: 도우미 클래스 없이 다운스트림 웹 API 호출
IAuthorizationHeaderProvider
인터페이스를 사용하여 인증 헤더를 가져오기로 결정한 경우 다음 코드는 웹 API를 호출하는 웹 API: 앱에 대한 토큰 획득에 표시된 코드 예를 계속합니다. 코드는 API 컨트롤러의 작업에서 호출됩니다. todolist라는 다운스트림 API를 호출합니다.
토큰을 가져온 후에는 이 토큰을 전달자 토큰으로 사용하여 다운스트림 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");
// ...
}