我在 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;
}
}
但我的日志显示我从未在 Items 中找到 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
过滤器和模块之间不一样的问题,但我不确定。
我尝试的另一个选项是在我的 Global.asax.cs 事件中订阅该FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider
事件Application_Start
,但当时 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
事件。