基本上,我的网站中有一项要求,即所有Cookie都必须受到保护。我正在尝试保护FormsAuthentication cookie,但是,我希望它能够在我的本地开发站点上设置SSL,但是实时站点仍然可以保护cookie。
此实时/开发状态存储在配置xml文件中。此文件包含运行该站点的每台计算机的设置。它可以通过Config.IsSecure
访问if (Config.IsSecure)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, login.Username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "User", FormsAuthentication.FormsCookiePath);
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
cookie.Path = FormsAuthentication.FormsCookiePath;
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication");
FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms;
formsAuthentication.RequireSSL = true;
cookie.Secure = true;
configuration.Save()
}
FormsAuthentication.SetAuthCookie(login.Username, false);
所以我在Save部分出错了。说有一个无法访问的临时文件。
知道如何解决这个问题吗?
Gurpreet
答案 0 :(得分:2)
我不太明白你要做什么,或者为什么你必须编写自定义代码才能做到这一点。我相信您可以配置表单身份验证以在web.config中使用SSL for cookies。然后只需要一个不同的web.config进行实时和开发。
requireSSL属性应该完全符合您的要求吗? (将cookie设置为仅安全,以便浏览器在安全连接时仅返回表单auth cookie。)
类似(在web.config中)
<authentication mode="Forms">
<forms timeout="30" loginUrl="/MyLogin.aspx" protection="All" requireSSL="True" />
</authentication>
答案 1 :(得分:1)
如果您不想管理两个web.config文件,另一个选择就是在本地计算机上安装证书 - 这真的不难做到。
我认为How to create a self-signed wildcard SSL certificate for IIS 6?的答案包含您需要的信息。只需确保正确设置主机名 - 您的计算机名称或本地主机名,或者在尝试连接到您的站点时会收到警告。
如果您使用VS2010 / .net 4,也可以在web.config上执行转换,我相信:http://msdn.microsoft.com/en-us/library/dd465318.aspx
答案 2 :(得分:0)
微米。如果不保护整个网站,您将无法保护cookie。使用下载页面的标准HTTP请求交换cookie,因此每个页面都必须是安全的。
您要保护的是登录表单......但这不是cookie。如果您在身份验证后重定向回http站点,则cookie仍然是不安全的。
<强>更新强>
HttpCookie.Secure只做一件事 - 如果没有SSL,它就不会将cookie传送给客户端。如果HTTP访问该站点,则生成的cookie标头将不包含您的cookie。 HttpCookie.Secure不会强制网站切换到SSL,只要我正确理解文档,它就会默默地破坏您的代码。