共用方式為


呼叫 Web API 的 Web API:取得應用程式的令牌

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

控制器中的程序代碼

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

不過,如果您確實想要手動取得令牌,下列程式代碼會顯示在 主控制器中使用 Microsoft.Identity.Web 來執行此動作的範例。 它會使用 REST API 呼叫 Microsoft Graph(而不是 Microsoft Graph SDK)。 通常,您不需要取得令牌,您必須建置您新增至要求的授權標頭。 若要取得授權標頭,您可以在 IAuthorizationHeaderProvider 控制器的建構函式中插入相依性插入服務(或使用 Blazor 時的頁面建構函式),並在控制器動作中使用。 這個介面有方法可產生包含通訊協定的字串(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 的詳細資訊,請參閱 呼叫Web API的Web API:呼叫 API

下一步

請移至此案例中的下一篇文章, 呼叫 API