asp mvc-设置应用程序';s cookie已被保护
本文关键字:cookie 保护 mvc- 设置 应用程序 asp | 更新日期: 2023-09-27 18:23:53
我正在开发一个asp-mvc应用程序,希望设置所有具有安全属性的cookie。我阅读了类似的线程,并在我的网络配置中添加了以下内容:
<httpCookies httpOnlyCookies="true" requireSSL="true" />
还创建了一个HttpModule,我已经通过web配置注册了它,并实现如下:我已经签入了debug,它得到的每个请求都是OnApplicationBeginRequest和OnApplicationEndRequest代码。
public class SecureSessionModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OnApplicationBeginRequest;
context.EndRequest += OnApplicationEndRequest;
}
void OnApplicationBeginRequest(object sender, EventArgs e)
{
HttpRequest currentRequest = ((HttpApplication)sender).Request;
HttpCookie requestCookie = RetrieveRequestCookie(currentRequest, "ASP.NET_SessionId");
if (requestCookie != null)
{
requestCookie.Secure = true;
}
}
void OnApplicationEndRequest(object sender, EventArgs e)
{
HttpRequest currentRequest = ((HttpApplication)sender).Request;
HttpCookie sessionCookie = RetrieveResponseCookie(((HttpApplication)sender).Response, "ASP.NET_SessionId");
if (sessionCookie != null)
{
sessionCookie.Secure = true;
}
}
private HttpCookie RetrieveResponseCookie(HttpResponse currentResponse, string cookieName)
{
HttpCookieCollection cookies = currentResponse.Cookies;
return FindTheCookie(cookies, cookieName);
}
private HttpCookie FindTheCookie(HttpCookieCollection cookieCollection, string cookieName)
{
for (int i = 0; i < cookieCollection.Count; i++)
{
if (string.Compare(cookieCollection[i].Name, cookieName, true, CultureInfo.InvariantCulture) == 0)
return cookieCollection[i];
}
return null;
}
现在,我打开了fiddler并在请求中:
Request sent 42 bytes of Cookie data:
ASP.NET_SessionId=XXXXXXXXXXXXXXXXXXX
and that's it
对此,"此响应未设置任何cookie"。
应用程序似乎忽略了我的所有设置。有什么建议吗?
您应该在更改cookie后使用HttpContext.Current.Response.SetCookie(cookie);
。仅仅更改cookie值并不能使cookie响应。