共用方式為


一個呼叫網頁 API 的網頁 API:為應用程式取得權杖

適用於帶有白色核取記號符號的綠色圓圈,表示以下內容適用於員工租戶。 員工租戶 (瞭解更多資訊

建置用戶端應用程式對象之後,請使用它來取得可用來呼叫 Web API 的令牌。

控制器中的程式碼

Microsoft.Identity.Web 會新增擴充方法,以提供用來呼叫 Microsoft Graph 或下游 Web API 的便利服務。 這些方法在 呼叫 Web API 的 Web 應用程式:呼叫 API 中有詳細的說明。 使用這些協助程式方法時,您不需要手動取得權杖。

但是,如果您想要以手動方式取得權杖,下列程式碼會示範使用 Microsoft.Identity.Web 在首頁控制器中執行此動作的範例。 它會使用 REST API 呼叫 Microsoft Graph (而非 Microsoft Graph SDK)。 通常,您不需要取得權杖,而是需要建立授權標頭並將其加入到您的請求中。 若要取得授權標頭,您可以透過控制器的建構函式 (如果使用 Blazor,則為頁面建構函式) 中的相依性插入來插入 IAuthorizationHeaderProvider 服務,並在控制器動作中使用。 這個介面有方法可產生包含通訊協定 (Bearer、Pop 等) 和權杖的字串。 若要取得代表使用者呼叫 API 的授權標頭,請使用 (CreateAuthorizationHeaderForUserAsync)。 若要取得授權標頭來代表應用程式本身呼叫下游 API,請在精靈案例中使用 (CreateAuthorizationHeaderForAppAsync)。

控制器方法會受到 [Authorize] 屬性的保護,確保僅有已驗證的呼叫可以使用 Web API。

[Authorize]
public class MyApiController : Controller
{
    /// <summary>
    /// The web API will accept only tokens 1) for users, 2) that have the `access_as_user` scope for
    /// this API.
    /// </summary>
    static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };

     static readonly string[] scopesToAccessDownstreamApi = new string[] { "api://MyTodolistService/access_as_user" };

     readonly IAuthorizationHeaderProvider authorizationHeaderProvider;

    public MyApiController(IAuthorizationHeaderProvider authorizationHeaderProvider)
    {
      this.authorizationHeaderProvider = authorizationHeaderProvider;
    }

    [RequiredScopes(Scopes = scopesToAccessDownstreamApi)]
    public IActionResult Index()
    {
        // Get an authorization header.
        IAuthorizationHeaderProvider authorizationHeaderProvider = this.GetAuthorizationHeaderProvider();
        string[] scopes = new string[]{"user.read"};
        string authorizationHeader = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(scopes);

        return await callTodoListService(authorizationHeader);
    }
}

如需有關 callTodoListService 方法的詳細資料,請參閱一個呼叫應用程式介面的網路 API:呼叫一個 API

下一步

請繼續進入此案例的下一篇文章:呼叫 API