asp mvc - 将应用程序的cookie设置为安全的

时间:2015-11-22 09:50:52

标签: c# asp.net-mvc cookies

我正在开发一个asp-mvc应用程序,并希望设置所有具有安全属性的cookie。我读了类似的线程,并在我的网络配置中添加了以下内容:

<httpCookies httpOnlyCookies="true" requireSSL="true" />

还创建了一个HttpModule,我已通过web config注册并实现如下: 我已经检查了调试以及它获取的每个请求到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;
    }

现在,我已经在请求中打开了提琴手:

Request sent 42 bytes of Cookie data:

ASP.NET_SessionId=XXXXXXXXXXXXXXXXXXX
and that's it

作为回应,“此回复未设置任何Cookie”。

似乎应用程序忽略了我的所有设置。请问有什么消息吗?

1 个答案:

答案 0 :(得分:0)

更改Cookie后应使用plt.close('all') 。只更改cookie值不会使cookie响应。