【发布时间】:2012-12-12 04:59:50
【问题描述】:
在 Medium Trust 中工作时,是否有一种简单的方法可以从 web.config 中读取anonymousIdentification 部分的 cookieName?
我想做的是阻止创建数千个匿名用户,因为:
- 人们关闭了 cookie,或者
- 访问者是没有 cookie 功能的蜘蛛/机器人。
我尝试通过检查 Application_BeginRequest 中是否存在表单身份验证或匿名标识 cookie 来实现此目的。如果没有 cookie,我会设置一个标志来阻止将任何内容保存到数据库中。
但为了做到这一点,我必须知道 cookie 的名称。为此,我尝试这样做:
AuthCookieName = FormsAuthentication.FormsCookieName;
var anonSection = (AnonymousIdentificationSection)WebConfigurationManager.GetSection("system.web/anonymousIdentification");
if (anonSection != null)
AnonCookieName = anonSection.CookieName;
虽然检索到 auth cookie 名称没有任何问题,但 WebConfigurationManager 会引发安全异常:System.Security.SecurityException: Request for the permission of type 'System.Configuration.ConfigurationPermission, System.Configuration, Version=4.0 .0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a' 失败。
我知道这是一个信任问题,因为当我给予高或完全信任时,异常就会消失。但是,这在 Medium Trust 中有效很重要,我无法修改 machine.config。
有没有办法在我的应用程序的 web.config 级别为anonymousIdentification 部分设置requirePermission="false"?
我是否必须将 web.config 加载到 XML 文档中并手动解析出来?
其他想法?
还有比这更好的吗?我只在Application_Start() 上运行过一次。
XmlDocument config = new XmlDocument();
config.Load(Server.MapPath("~/Web.config"));
XmlNode anonSection = config.SelectSingleNode("configuration/system.web/anonymousIdentification");
if (anonSection != null)
{
XmlAttribute nameAttr = anonSection.Attributes["cookieName"];
if (nameAttr != null)
AnonCookieName = nameAttr.Value;
}
if (string.IsNullOrWhiteSpace(AnonCookieName))
AnonCookieName = ".ASPXANONYMOUS";
【问题讨论】:
-
“未经身份验证的用户”可以保存到数据库吗?恕我直言,如果他们这样做了,我看不出你为什么需要区分(除非我遗漏了什么)。要查明用户是否经过身份验证,
HttpRequest.IsAuthenticated不够吗? -
未经身份验证的用户数据也将保存到数据库中。
-
那不会简化为
HttpRequest.IsAuthenticated(真或假)吗? -
对不起,我没有关注。 IsAuthenticated 不只是告诉我用户是否已登录(具有 FormsAuthentication cookie)吗?这对了解是否存储有关匿名用户的数据有何帮助?如果用户禁用了 cookie,anonymousId 将在每次请求时更改,从而创建一个新的匿名用户和相关数据。
-
如果
.IsAuthenticated == false,那么用户是“匿名”或禁用cookies,或机器人,假设在您的应用程序中“需要”身份验证。否则,如果是检查客户端是否可以处理cookie的问题,那么它甚至不必是身份验证cookie...
标签: asp.net web-config webconfigurationmanager