一段时间以来,我一直在努力解决这个问题,特别感谢Lars Kemmann和Tratcher,我相信公认的方法如下:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions { }
);
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = ConfigurationManager.AppSettings["ida:Wtrealm"],
MetadataAddress = ConfigurationManager.AppSettings["ida:FedMetadataURI"]
}
);
您将默认身份验证类型配置为“Cookie 身份验证”以使 WsFederation 工作似乎违反直觉,但是这些实际上只是用于标识每个中间件的字符串(这允许您注册相同类型的多个中间件次,例如),他们评估如下:
CookieAuthenticationDefaults.AuthenticationType
=“饼干”
WsFederationAuthenticationDefaults.AuthenticationType
=“联邦”
这里发生的情况是,我们告诉 OWIN 默认情况下应该使用标记为“Cookies”的中间件来验证请求,然后我们添加 CookieAuthentication 中间件(默认情况下,它从CookieAuthenticationDefaults.AuthenticationType
值中标记为“Cookies”,所以我们不必须编写任何额外的代码来设置它),最后我们添加了 FederationAuthentication 中间件(这被标记为WsFederationAuthenticationDefaults.AuthenticationType
- 即“Federation”),我的理解是,Federation 中间件利用 Cookie 中间件来管理其与身份验证相关的 cookie。
剩下要做的就是配置您的应用程序以在您选择的时间调用中间件,这可以通过多种方式实现,其中一些方式如下:
- 通过返回 HTTP 401 响应
- 通过使用
[Authorize]
MVC 控制器上的属性
- 通过调用 OWIN Context
IAuthenticationManager
的Challenge
方法(传入联邦中间件的标签)
当我在这里问这个问题时,Lars 回答了一个关于如何为所有请求请求身份验证的简洁示例,然后我将其捆绑到 OWIN 管道中,如下所示:
app.Use(
(context, continuation) =>
{
if (
(context.Authentication.User != null) &&
(context.Authentication.User.Identity != null) &&
(context.Authentication.User.Identity.IsAuthenticated)
)
{
return continuation();
}
else
{
context.Authentication.Challenge(WsFederationAuthenticationDefaults.AuthenticationType);
return Task.Delay(0);
}
}
);
请注意,在上面的第一个示例中,为了便于维护,我将Wtrealm和MetadataAddress值移动到了我的配置文件中,它们只是简单的应用程序设置:
<appSettings>
<add key="ida:Wtrealm" value="[app-uri]" />
<add key="ida:FedMetadataURI" value="https://[adfs-server]/federationmetadata/2007-06/federationmetadata.xml" />
</appSettings>
我希望这有帮助。