【问题标题】:What is the difference between UseWindowsAzureActiveDirectoryBearerAuthentication with UseOpenIdConnectAuthentication?UseWindowsAzureActiveDirectoryBearerAuthentication 与 UseOpenIdConnectAuthentication 有什么区别?
【发布时间】:2018-10-14 10:32:52
【问题描述】:

我有注册到 azure AD 的 webapi。 在 Startup.Auth.cs 中有以下代码

   public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                Authority = Authority,
                PostLogoutRedirectUri = PostLogoutRedirectUri
            });

当我在浏览器中运行这个 webapi 时,它会要求登录,登录成功后可以看到所有 api 的 url。

我正在尝试从注册到同一天蓝色 AD 的 Web 应用程序访问此安全 API。

当我在 Webapp 中使用 AcquireTokenAsync 为这个 webapi 生成访问令牌时,它可以工作,但会给出登录 html 页面作为响应。

为避免这种情况,我尝试使用 AcquireTokenSilentAsync 生成静默令牌,但出现异常 unable to generate token cache not found 但缓存键仍然存在异常。

在一些 google git post 建议在 WebApi 中使用UseWindowsAzureActiveDirectoryBearerAuthentication 后,他们说当从 webapp 调用而不是登录页面输出时,它将返回 api 的输出,但它不起作用。

 app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Audience = ConfigurationManager.AppSettings["ida:Audience"],
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = false
                    }
                });

【问题讨论】:

    标签: c# .net azure azure-active-directory


    【解决方案1】:

    API 不应要求用户登录。 Bearer 令牌身份验证的第二个选项是正确的。这意味着您的客户端应用需要获取访问令牌并将其与 HTTP 请求一起传递。

    AcquireTokenAsyncAcquireTokenSilentAsync 的工作方式与您的想法有些不同。 第一个接受一些参数,然后调用 AAD 授权的 /oauth2/token 端点以获取访问令牌除非它已经在缓存中具有访问令牌。 静默版本只检查缓存,如果找不到则抛出异常。

    因此,您的客户端应用程序通常会使用AcquireTokenAsync 变体之一来获取访问令牌和刷新令牌。 当您这样做时,ADAL 会将令牌存储在您为其提供的令牌缓存中(或默认情况下的内存缓存)。 然后稍后在您的代码中,您可以使用静默版本来获取令牌,因为您可以期望它们在缓存中。

    【讨论】:

    【解决方案2】:

    ASP.NET OWIN 组件包括专门设计用于通过 Azure AD 和 OAuth2 持有者令牌访问保护 Web API 的中间件。 OpenID Connect 中间件 (UseOpenIdConnectAuthentication) 在请求到达为浏览器提供 UX 的 UX 控制器时触发,而 Azure AD OAuth2 不记名令牌中间件 (UseWindowsAzureActiveDirectoryBearerAuthentication) 仅在请求针对 Web API 时触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 2013-03-14
      • 2018-09-14
      • 2014-01-03
      • 2021-12-22
      • 2017-10-25
      • 2011-06-09
      • 2021-05-11
      相关资源
      最近更新 更多