Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
PilotBob Avatar asked Nov 05 '25 08:11

PilotBob


1 Answers

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;
            }
        }
    }
}
like image 51
David J Anderson Avatar answered Nov 07 '25 15:11

David J Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!