asp.net-mvc-5antiforgerytoken

How can I set SameSite=None on the AntiForgertyToken cookie in MVC5?


We are implementing cross site scripting protection in MVC5 by using the built in ValidateAntiForgeryToken attribute and @Html.AntiForgeryToken() helper.

This all works. However, our app runs in a frame that is in a different domain. So, we need to set the cookie to SameSite=none (as we have done with session and auth cookies).

I can't find a way to configure the cookie to include this setting.

I have tried to create an OWIN middle ware to check the cookies on the way out and update it, but the cookie collection in the response in the OWIN context is read only.

How can I get this setting on the cookie?


Solution

  • Adding this to Global.asax.cs to set the token to SameSite = none should fix it:

    protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
    {
        // This code will mark the __RequestVerificationToken cookie SameSite=None 
        if (Request.Cookies.Count > 0)
        {
            foreach (string s in Request.Cookies.AllKeys)
            {
                if (s.ToLower() == "__requestverificationtoken")
                {
                    HttpCookie c = Request.Cookies[s];
                    c.SameSite = System.Web.SameSiteMode.None;
                }
            }
        }
    }