首页 > 解决方案 > 如何从同一 Azure AD 中的另一个 Web 应用程序访问 Web api?

问题描述

我在上面托管了一个 web ProductInfoapiazure and register that application into Azure AD.

我有另一个web app UIProduct,这个 Web 应用程序want to access the web api ProductInfo都在同一个域和同一个 Azure AD 中。

我怎样才能访问 web ProductInfoapi web app UIProduct?我需要再次生成任何令牌吗?

任何示例代码都会有所帮助。取自此链接的代码示例

成功登录后我在主页然后我点击关于我写这个的页面

    public async System.Threading.Tasks.Task<ActionResult> About()
    {
        AuthenticationResult result = null;

        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
        ClientCredential credential = new ClientCredential(clientId, clientSecret);
        result = await authContext.AcquireTokenSilentAsync("App ID URI", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

        HttpClient client = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://demotest.azurewebsites.net/api/getdata");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        HttpResponseMessage response = await client.SendAsync(request);

出现异常 - “无法以静默方式获取令牌,因为在缓存中未找到令牌。调用方法 AcquireToken”

标签: c#azureasp.net-web-apiazure-active-directory

解决方案


您需要在Azure 门户中将这两个应用程序都注册为 Web 应用程序/API。

然后在您的 Web API 中,设置App ID URI并创建您想要公开的任何范围。如果这是您将使用的唯一客户端,您可能只能拥有一个Access范围,但请记住,这是最终用户在同意您的应用程序时将看到的内容。

在您的网络应用程序中,您将能够Required Permissions为这个新的网络 API 和范围设置一个。这表明客户端应该需要对此 Web API 的同意,并且可以为其授予访问令牌。

此代码示例涵盖了这个确切的场景。

Web API 基础文档还涵盖了与此方案相关的一些概念信息


推荐阅读