我在MVC 3站點上使用WS Federated(Claim Aware)身份驗證,並且遇到問題時仍然無法讓發送JSON的一些API控制器返回重定向認證失敗。我有一個叫做API的Area,帶有幾個只返回JSON的控制器,這些控制器都從同一個基類繼承而來。我想發送合法的401錯誤響應,而不是默認發生的302重定向。防止XmlHttpRequest在.Net MVC WS-Federation站點中重定向響應
我跟一些方向,我發現在演唱會與過濾器我把我的API控制器動作創建自定義WSFederationAuthenticationModule
:
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
不是過濾器和模塊之間的相同問題,但我不知道。
我試過的另一個選擇是在我的Global.asax.cs的Application_Start
事件中訂閱FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider
事件,但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
事件。
最後!感謝+1) – cleftheris 2012-05-25 13:36:52