Simant
Simant

Reputation: 4360

How to set sameSite=None in Asp.Net MVC generated cookies?

I have an asp.net MVC application and I want to set all the cookies sameSite=None for the application. I have set the below lines in the web.config but the application sets the cookies without SameSite=None. I have added the below two configurations in the web.config. See the below screenshot having both .AspNet.ApplicationCookie and __RequestVerificationToken cookies placed without sameSite=None. Please help.

<system.web>
        <httpCookies requireSSL="true"/>
        <sessionState cookieSameSite="None"/>
</system.web>

enter image description here

Upvotes: 3

Views: 1401

Answers (1)

Eassa Nassar
Eassa Nassar

Reputation: 1230

i did it from the code and it worked
in global.asax.cs:

 public class MvcApplication : HttpApplication
                {
                
                   protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
                   {
        .....
                        if (Request.Cookies.Count > 0)
                        {                        
                            foreach (string s in Request.Cookies.AllKeys)
                            {
                                HttpCookie c = Request.Cookies[s];
                                c.SameSite = System.Web.SameSiteMode.None;
                                Response.Cookies.Set(c);
                            }
                       }
        ....
                    }
                }

if you want for specific cookie

 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);
                    }
                }
            }

Upvotes: 4

Related Questions