Context.User.Identity.IsAuthenticated总是经过身份验证?

时间:2011-03-03 17:25:55

标签: asp.net iis forms-authentication

我正在尝试创建一个httphandler,它将拦截我们网站上的示例pdf文件。如果我只是尝试连接到测试网址,那么httphandler可以在我的开发机器甚至本地发布的网站中正常工作: https://test.com/admin/_/sample_reports/sample.pdf我将被发送到无效访问页面。

当我尝试转到它提供PDF文档的URL时,将它推送到我们的IIS6机器。 context.User.Identity.IsAuthenticated始终显示为true。

我正在使用表单身份验证。下面是我用作处理程序的代码。

public void ProcessRequest(HttpContext context)
{
    if (context.User.Identity.IsAuthenticated)
    {
        string SampleURL = context.Request.AppRelativeCurrentExecutionFilePath;

        context.Response.Buffer = true;
        context.Response.Clear();
        using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(SampleURL),FileMode.Open))
        {
            int length = (int)fs.Length;
            byte[] buffer;

            using (BinaryReader br = new BinaryReader(fs))
            {
                buffer = br.ReadBytes(length);
            }

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.ContentType = "application/pdf";
            context.Response.BinaryWrite(buffer);
            context.Response.End();
        }
    }
    else
    {
        context.Response.Redirect(
           "~/Error/invalid_access.aspx");
    }}
web.config中的

我有以下表格认证:

<authentication mode="Forms">
  <forms name="Sample.Web" loginUrl="~/Security/" defaultUrl="~/default.aspx" protection="All" timeout="60" path="/" requireSSL="false" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseDeviceProfile" domain="">
  </forms>
</authentication>
<authorization>
  <deny users="?"/>
</authorization>

3 个答案:

答案 0 :(得分:3)

当身份验证cookie仍然设置且表单身份验证仍然有效(未过期)时,

Context.User.Identity.IsAuthenticated属性设置为true

  

在Forms身份验证的情况下,   表单身份验证模块使用   加密的身份验证票证   包含在身份验证Cookie中   验证用户。一旦它有了   这样做,它取代了   GenericIdentity in   Context.User.Identity有一个   返回的FormsIdentity对象   来自true的{​​{1}}   属性。

所以,你的auth cookie还活着;可能是因为调用FormsAuthenticationRedirectFromLoginPage之类的SetAuthCookie方法正在设置auth cookie;或者只是被遗忘的饼干。

最好使用HttpRequest.IsAuthenticated代替IsAuthenticated作为示例。它会检查Context.User.Identity.IsAuthenticatedHttpContext.User是否不是HttpContext.User.Identitynull属性是否设置为HttpContext.User.Identity.IsAuthenticated。在你的情况下,例如true HttpContext.User您的代码会抛出null

答案 1 :(得分:2)

你确定吗

  

当我尝试转到它提供PDF文档的URL时,将它推送到我们的IIS6机器。 context.User.Identity.IsAuthenticated始终显示为true。

这个.PDF请求可能已经由IIS 6静态文件处理程序处理,而不是IIS 6上的HTTP处理程序。

答案 2 :(得分:0)

您需要使用ProcessRequest

public void ProcessRequest(HttpContext context)
{
    if (!context.User.Identity.IsAuthenticated)
    {
         context.Response.Redirect(
           "~/Error/invalid_access.aspx");
    }

}

编辑:可能是IIS的罪魁祸首那么,你有以下几套吗?在IIS中,对于使用表单身份验证的所有应用程序,匿名访问 已启用

<system.web>
  <authorization>
    <deny users="?" />
  </authorization>
</system.web>