来自AJAX的表单身份验证和POST请求

Ale*_*lex 6 asp.net forms-authentication

我们有一个受表单身份验证保护的ASP.NET应用程序 该应用程序大量使用MS AJAX来调用其Web服务.

当表单身份验证超时,并且GET -request发生时 - 一切都很好(用户被重定向到登录页面).

但是当表单身份验证超时并发生POST请求时(ajax) - 没有重定向发生,而应用程序返回"401 unathorized",浏览器提示输入用户名和密码(不是登录表单,而是浏览器内置对话框) ).当然输入任何用户名/密码永远不会有帮助.

我该如何处理?

更新:用firebug查看之后,我发现常规POST请求重定向到登录正常,只有网络服务调用才会抛出"401 Unauthorizes".常规请求和Web服务之间的区别是URL.对于常规的后请求,这是"page.aspx",对于webservices,是"service.asmx/MethodName"...

Ale*_*lex 2

好的,回答我自己的问题。

在研究这个问题并进行更多研究后,我发现当网络应用程序受 Forms-Authentication 保护并且用户未经身份验证时,会发生以下情况:

  • 如果是 GET 请求 - 用户将被重定向到登录页面。
  • 如果它是对页面的 POST 请求 - 用户将被重定向到登录页面。
  • 如果是对 Web 服务的POST 请求- 用户会收到 401-未经授权

这就是 ASP.NET 的工作原理

如果 AJAX(xmlHttpRequest 对象)调用 Web 服务并返回 401 - 当然,浏览器会显示一个弹出登录框。

现在,您应该做的是向 Application_PostAuthenticateRequest 添加一些代码,以防止为 Web 服务抛出 401 错误。

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    if (Request.RequestType == "POST" //if its POST
        && !User.Identity.IsAuthenticated //if user NOT authed
        && !HasAnonymousAccess(Context) //if it's not the login page
        )
    {
        //lets get the auth type
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        SystemWebSectionGroup grp = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
        AuthenticationSection auth = grp.Authentication;
        //if it FORMS auth
        if(auth.Mode== AuthenticationMode.Forms)
        {

            //then redirect... this redirect won't work for AJAX cause xmlHttpRequest can't handle redirects, but anyway...
            Response.Redirect(FormsAuthentication.LoginUrl, true);
            Response.End();

        }
    }
}
public static bool HasAnonymousAccess(HttpContext context)
{
    return UrlAuthorizationModule.CheckUrlAccessForPrincipal(
        context.Request.Path,
        new GenericPrincipal(new GenericIdentity(string.Empty), null),
        context.Request.HttpMethod);
}
Run Code Online (Sandbox Code Playgroud)