How to set vaue of attribute samesite on the cookie __RequestVerificationToken_Lw__
Asked Answered
P

1

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__
Penman answered 17/6, 2019 at 15:46 Comment(1)
wild guess.. set it up in your startup class ? services.AddAntiforgery(options => { options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict ; });Braeunig
O
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);
                    }
                }
            }           
        }
 }
Occlusive answered 14/1, 2020 at 11:8 Comment(4)
SameSite not available before .NET Framework 4.7.2 :-(Tithonus
@PaulB., in earlier .Net you can use c.Path += "; SameSite=Strict";. (NB: you may want to check for an existing SameSite-part first.)Anathematize
This LOOKS LIKE it actually adds the cookie a second time, not overwrites the cookieBelt
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://<websiteurl>/ -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.Luminescence

© 2022 - 2024 — McMap. All rights reserved.