【问题标题】:Adding location header on response from Microsoft.Owin.Security.OpenIdConnect middleware在来自 Microsoft.Owin.Security.OpenIdConnect 中间件的响应中添加位置标头
【发布时间】:2016-03-31 13:49:07
【问题描述】:

我们已经使用 IndentityServer 和 Owin 自托管 Web API 实现了 OAuth。每当客户端尝试访问我们经过身份验证的端点时,我们都会使用 Microsoft.Owin.Security.OpenIdConnect 中间件来拦截调用并将其重定向到 IndentityServer 进行身份验证。在 API 调用的情况下,我们不希望返回 302,而是返回带有位置标头的 401,其中包含 IdentityServer 的 url。我们可以通过设置让 OWIN 中间件返回 401

AuthenticationMode = AuthenticationMode.Passive

但我们无法添加位置标头。我们如何做到这一点?我们已经尝试设置标题(参见下面的代码),但它不起作用。似乎响应是由中间件在内部构建的。

appBuilder.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = idSrvUri.ToString(),
                AuthenticationType = WebServiceConstants.OAuthAuthType,
                ClientId = "beocloud",
                Scope = "openid profile roles",
                ResponseType = "id_token token",
                AuthenticationMode = AuthenticationMode.Passive,
                SignInAsAuthenticationType = WebServiceConstants.OAuthAuthType,
                UseTokenLifetime = false,


                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            n.ProtocolMessage.RedirectUri = n.Request.Scheme + "://" + n.Request.Host + "/";
                            n.Response.Headers.Add("Location", new []{n.ProtocolMessage.CreateAuthenticationRequestUrl()});
                        }

                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;

                            }
                        }

                        return Task.FromResult(0);
                    }
                }
            });
        }

【问题讨论】:

    标签: c# http owin middleware identityserver3


    【解决方案1】:

    这是与 MVC 代码一起托管 Web API 的问题 - 您在其 API 端使用了错误的安全中间件。 OIDC 中间件假定 HTTP 调用来自它可以重定向的浏览器窗口。

    我建议将您的 API 拆分为单独的主机和管道,并使用基于令牌的安全架构和中间件。我们在 github repo 上有很多这种模式的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 2015-04-05
      • 2019-01-07
      • 1970-01-01
      • 2021-12-28
      • 2015-04-10
      相关资源
      最近更新 更多