我在 MVC 3 站点上使用 WS 联合(声明感知)身份验证,并且在身份验证失败时无法阻止某些发送 JSON 的 API 控制器返回重定向。我有一个名为 API 的区域,其中有几个仅返回 JSON 的控制器,这些控制器都继承自同一个基类。我想发送合法的 401 错误响应,而不是默认情况下发生的 302 重定向。
我遵循了一些创建自定义的指示WSFederationAuthenticationModule
与我在 API 控制器操作上放置的过滤器配合使用:
public class WSFederationServiceAuthenticationModule : WSFederationAuthenticationModule
{
private static Log4NetLoggingService logger = new Log4NetLoggingService();
public const string IsServiceIndicator = "ROIP.IsService";
protected override void OnAuthorizationFailed(AuthorizationFailedEventArgs e)
{
base.OnAuthorizationFailed(e);
var isService = HttpContext.Current.Items[IsServiceIndicator];
if (isService != null)
{
logger.Info("WSFedService: Found IsService");
e.RedirectToIdentityProvider = false;
}
else
{
logger.Info("WSFedService: Did not find IsService");
}
}
}
public class WSFederationServiceAuthAttribute : ActionFilterAttribute
{
private static Log4NetLoggingService logger = new Log4NetLoggingService();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// Set an item that indicates this is a service request, do not redirect.
logger.Info("WSFedService: Setting IsService");
HttpContext.Current.Items[WSFederationServiceAuthenticationModule.IsServiceIndicator] = 1;
}
}
但我的日志记录显示我从未在项目中找到 IsService 项目:
{INFO}02/29 03:39:21 - WSFedService: Setting IsService
{INFO}02/29 03:39:32 - WSFedService: Setting IsService
{INFO}02/29 03:39:32 - WSFedService: Setting IsService
{INFO}02/29 03:50:39 - WSFedService: Did not find IsService
{INFO}02/29 03:53:16 - WSFedService: Did not find IsService
{INFO}02/29 03:53:29 - WSFedService: Did not find IsService
我认为这可能是一个问题HttpContext.Current
过滤器和模块之间不一样,但我不确定。
我尝试的另一个选择是订阅FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider
事件在Application_Start
我的 Global.asax.cs 的事件,但当时 WSFederationAuthenticationModule 为空。
private void ConfigureWSFederationAuthentication()
{
bool hasFederatedAuthentication = false;
try
{
if (FederatedAuthentication.WSFederationAuthenticationModule != null)
{
hasFederatedAuthentication = true;
}
}
catch
{
hasFederatedAuthentication = false;
}
if (hasFederatedAuthentication)
{
Logger.Info("WSFederation: Registering for Event Handler");
FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += (s, e) =>
{
var msg = string.Empty;
try
{
if (HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
e.Cancel = true;
msg = "Found XMLHttpRequest header";
}
else
{
msg = "Did not find XMLHttpRequest header";
}
}
catch (Exception ex)
{
msg = "WSFederation: Event Handler Error: " + ex.Message;
}
Logger.Info("WSFederation: Redirecting from Event Handler: " + msg);
};
}
else
{
Logger.Info("WSFederation: Null WSFederationAuthenticationModule");
}
}
我想知道如何让第一个选项起作用,或者我应该在哪里订阅RedirectingToIdentityProvider
event.