8

I have an antirforgery token(@Html.AntiForgeryToken()) on a cshtml page, which generates a cookie RequestVerificationToken_Lw. The attribute values on this cookie are HTTP and Secure. But I need the SameSite also to be set. How do I achieve this?

@Html.AntiForgeryToken()

__RequestVerificationToken_Lw__
Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
user2990342
  • 91
  • 1
  • 3
  • 1
    wild guess.. set it up in your startup class ? _services.AddAntiforgery(options => { options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict ; });_ – AardVark71 Jun 21 '19 at 15:50

1 Answers1

4

Can this help?

in Global.asax.cs

 public class MvcApplication : System.Web.HttpApplication
 {

        protected void Application_PreSendRequestHeaders(object sender,EventArgs e) {
            // This code will mark the __RequestVerificationToken cookie SameSite=Strict 
            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.Strict;
                        Response.Cookies.Set(c);
                    }
                }
            }           
        }
 }
Maayan Hope
  • 1,482
  • 17
  • 32
  • `SameSite` not available before .NET Framework 4.7.2 :-( – Paul B. Jan 16 '20 at 10:07
  • 2
    @PaulB., in earlier .Net you can use `c.Path += "; SameSite=Strict";`. (NB: you may want to check for an existing `SameSite`-part first.) – Yahoo Serious Feb 13 '20 at 13:50
  • This LOOKS LIKE it actually adds the cookie a second time, not overwrites the cookie – scott.korin Aug 16 '21 at 19:57
  • I would advise against this. The code as written loops through the cookies being sent by the client (Request.Cookies) and adds them to the Response. You can confirm with curl by trying `curl -I https:/// -H "Cookie: __RequestVerificationToken=BadCookie; path=/; secure; HttpOnly"`. The server will return `set-cookie: __RequestVerificationToken=BadCookie; path=/; secure; HttpOnly; SameSite=Lax` You will also see two Set-Cookie headers returned because the server is not being sent the VerificationToken that it expects. – Josh Brule Jun 01 '22 at 21:04