防止 .Net MVC WS-Federation 站点中的 XmlHttpRequest 重定向响应

2024-05-01

我在 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.


我想我已经找到了这个问题的答案,并想回头为世界上可能遇到这个问题的其他人留下答案。

我的问题是HttpContext.Current.Items我的之间不匹配ActionFilterAttributeWSFederationAuthenticationModule所以我最终检查了上下文并添加了一些类似于Phil Haacks 表单重定向抑制示例 http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

这是我更新的自定义内容WSFederationAuthenticationModule好像:

public class WSFederationServiceAuthenticationModule : WSFederationAuthenticationModule
{
    private static Log4NetLoggingService logger = new Log4NetLoggingService();

    protected override void OnAuthorizationFailed(AuthorizationFailedEventArgs e)
    {
        base.OnAuthorizationFailed(e);            

        var context = HttpContext.Current;
        var req = context.Request;
        var resp = context.Response;

        if (req == null || resp == null)
        {
            logger.Info("WSFedService: Did not find Request or Response");
            return;
        }

        if ((resp.StatusCode == 302 || resp.StatusCode == 401) && req.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            logger.Info("WSFedService: Found Redirect and Header");
            e.RedirectToIdentityProvider = false;
        }
        else
        {
            logger.Info(string.Format("WSFedService: Did not find redirect status code or XMLHttpRequest Header: {0}", resp.StatusCode));
        }

    }
}

当然,您需要将其添加到 web.config 中以代替默认的身份验证模块:

<system.web>
    <httpModules>
        <!-- Old and Busted...
        <add name="WSFederationAuthenticationModule"
           type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        -->

        <!-- New Hotness... -->
        <add name="WSFederationAuthenticationModule"
           type="MyApp.Web.Authentication.WSFederationServiceAuthenticationModule, MyApp.Web" />
    </httpModules>
</system.web>

<system.webServer>
    <modules>
        <!-- Old and Busted...
        <add name="WSFederationAuthenticationModule"
           type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
           preCondition="managedHandler"/>
        -->

        <!-- New Hotness... -->
        <add name="WSFederationAuthenticationModule"
           type="MyApp.Web.Authentication.WSFederationServiceAuthenticationModule, MyApp.Web"
           preCondition="managedHandler"/>

    </modules>
</system.webServer>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

防止 .Net MVC WS-Federation 站点中的 XmlHttpRequest 重定向响应 的相关文章

随机推荐

  • 我在 iText 中的希伯来语文本是左对齐的

    我使用以下代码在 iText 中生成希伯来语文本 它工作得很好 创建希伯来字体 并使文本从右到左流动 但文本是左对齐而不是右对齐 谁能帮我让它右对齐吗 请注意 我尝试使多列文本右对齐 并使段落右对齐 但无济于事 Thanks static
  • 设置 setAttribute() 进行行格式、line_spacing、SPACING_AFTER、SPACING_BEFORE

    我正在尝试从模板文件在 Google 文档中生成报告 当它复制文档时 它会将所有格式重置为用户的默认格式 而不是原始文档中的格式 我尝试了以下方法来尝试在文档 tableRow 和 tableCell 级别上设置格式 但创建报告时行距为 1
  • 了解 AVCaptureSession 会话预设的分辨率

    我正在 iOS 中访问相机并使用会话预设 如下所示 captureSession sessionPreset AVCaptureSessionPresetMedium 相当标准的东西 但是 我想提前知道由于此预设而获得的视频的分辨率 特别是
  • 有没有办法用 Vim 自动重新格式化大括号?

    我想重新格式化一些代码 如下所示 if cond foo to if cond foo 由于这是C代码 所以我一直在看cindent cinoptions与使用 但它似乎不处理多行规则 我一直在看formatoptions与使用gq 而且似
  • 如何在我的网站中创建全局搜索[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 如何在我的网站中创建全局搜索 该网站是内部网站 无法在网上使用 我无法使用 Google 搜索来实现此目的 我的信息全部存储在不同的
  • 增加 Instagram API 350 个请求限制

    根据开发人员文档 客户端每小时可以发出 5000 个请求 但目前我的应用程序被限制为每小时 350 个请求 我收到的错误代码是 400 消息是 已超出每小时最大请求数 您在过去一小时内发出了 XXX 个请求 超过了允许的 350 个请求 您
  • 静态资源的 URI 中的上下文路径,我真的需要指定它吗?

    我有一个简单的网络应用程序 webapp static images a gif pages test html WEB INF pages test jsp 在test html中 有 img src static images a gi
  • 背景重复 x/y 在 Firefox/Safari 中不起作用

    我有下面的代码表明background repeat x y由于某些原因 它在 FireFox 上不起作用 它只是删除了这些样式 但并不是说它们是不正确的 它们没有在某处被覆盖 当我尝试将这些风格结合在一起时 background 它也将其
  • FORTRAN 写()

    在开始之前 我必须先声明一下 我是 FORTRAN 的新手 我正在维护 1978 年的一段遗留代码 它的目的是从文件中读取一些数据值 处理这些值 然后将处理后的值输出到另一个文本文件 给出以下 FORTRAN 代码 INTEGER NM S
  • 使用 FocusScope.of(context).unfocus() 重建小部件树

    我有这个例子 override Widget build BuildContext context return Scaffold body SafeArea child Padding padding const EdgeInsets a
  • 未找到列:1054 未知列 laravel

    所以我尝试用 laravel 制作一个表单 但除了新版本之外 他们删除了表单 但我可以让它运行 所以这里是 Route post register function user new User user gt u n Input get u
  • URL中的gs_upl是什么意思?

    在任何谷歌搜索 URL 中 gs upl 是什么意思 例如 那么 gs upl 1045l1663l0l3648l4l4l0l0l0l0l258l682l0 3 1l4l0 在这里意味着什么 从构建的脚本gs upl j 我找到 funct
  • jquery脉动文本

    我正在使用 jquery 来使文本脉动 一切都很好 但我无法理解某些事情 我只想脉动 x 次 然后停止 我正在使用以下代码来使类产生脉动 document ready function function pulsate pulsate an
  • 何时使用Statement而不是PreparedStatement?

    何时使用语句而不是准备好的语句 我想在没有参数的查询中使用语句 但为什么不使用准备好的语句 对于没有参数的查询 哪一个更快 我想在没有参数的查询中使用语句 但为什么不使用准备好的语句 那还差得远 PreparedStatements 用于返
  • aria2c - 有什么办法只保留失败下载的列表吗?

    我在用aria2c下载以文本文件形式组织的相当大的 url 列表 6000 基于此gist https gist github com jonbakerfish 0f7877c050b648169e0958ea2e2c6aca 我使用以下脚
  • 为什么 golang 堆配置文件中的“Total MB”小于顶部的“RES”?

    我有一个用 go 编写的服务 在运行时需要 6 7G 内存 RES 在顶部 所以我使用 pprof 工具试图找出问题所在 go tool pprof pdf http
  • 从 DOM 中删除一行后更新 jQuery Tablesorter 插件

    我目前有一些代码隐藏已删除的行 然后使用 remove 函数将其删除 然而 我很难让它保持 删除 状态 因为每次我刷新表排序分页器插件或我正在使用的过滤器插件插件时 删除的行会重新出现 因为它们当然被缓存了 目前的代码很简单 目前有小部件更
  • 使用 ls 和 grep 列出具有特定扩展名的文件

    我只想从当前目录获取文件 并且只输出 mp4 mp3 exe 文件 没有其他内容 所以我想我可以这样做 ls grep mp4 grep mp3 grep exe 但不会 因为第一个 grep 将仅输出 mp4 因此其他 2 个 grep
  • 如何更改詹金斯主目录位置?

    简单的问题 如何更改jenkins主目录位置 默认情况下它指向 var lib jenkins 而我希望它指向 mnt home jenkins 我已将 JENKINS HOME 更改为 mnt home jenkins 但这对我没有帮助
  • 防止 .Net MVC WS-Federation 站点中的 XmlHttpRequest 重定向响应

    我在 MVC 3 站点上使用 WS 联合 声明感知 身份验证 并且在身份验证失败时无法阻止某些发送 JSON 的 API 控制器返回重定向 我有一个名为 API 的区域 其中有几个仅返回 JSON 的控制器 这些控制器都继承自同一个基类 我