Conditionally setting SameSite cookie attribute

I have a requirement to set the SameSite cookie attribute based on UserAgent. Essentially, we have a significant number of clients on an older, pre-76 version of Chrome (via embedded chromium). They’re in an environment where they will not be able to upgrade any time soon. We need to support them as well as clients that are on post v76 of Chrome (when the SameSite support was introduced).

Having read this thread I’ve upgraded the solution to .NET Framework 4.8 and ServiceStack 5.8.

I’ve overridden the HttpCookieFilter (which takes a System.Web.HttpCookie) and SetCookieFilter (which takes IRequest object a System.Net.Cookie).

The SameSite property only exists on the HttpCookie and not the Cookie type. Using the SetCookieFilter override I can interrogate the IRequest argument to determine the useragent but I cannot set the SameSite property as the Cookie type does not contain it. Conversely, on the surface, it would seem that using the HttpCookieFilter override I cannot obtain the useragent (although I could try the System.Web.HttpContext.Current.Request.UserAgent which still feels a bit hacky) but can set the HttpCookie SameSite property.

Without resorting to constructing a hacky workaround, setting the cookie as mythz tentatively suggests in post 13 of the aforementioned thread, is there a better way of achieving my goal?

If you’ve upgraded to .NET Framework v4.8 you can use HttpCookieFilter in .NET Framework, e.g:

public override void HttpCookieFilter(HttpCookie cookie)
{
    cookie.SameSite = SameSiteMode.None;
}

Why can’t you set it here?

Since this is .NET Framework you can access the Request Context from the HttpContext.Current singleton, e.g:

HttpRequest aspReq = HttpContext.Current.Request;

You can also create a new IRequest from HttpContext.Current with:

IRequest req = HostContext.TryGetCurrentRequest();

And use HttpContext.Current.Request.UserAgent to get the user agent?

If this is using ASP .NET, yes.

Thanks. Purely from the point of view of simply accessing the useragent is there any reason to favour:

HostContext.TryGetCurrentRequest();

over:

HttpRequest aspReq = HttpContext.Current.Request;

Not for accessing the UserAgent, use HttpContext.Current directly.

Only really useful if you need to to use one of IRequest extension methods or need to call an API that accepts an IRequest, otherwise TryGetCurrentRequest() is being created from the same HttpContext.Current singleton.

Thought it might do something like that. Thanks for clarifying.

1 Like

Presumably, if we were planning on migrating to .NET Core (5) in the near future, HostContext.TryGetCurrentRequest() may be a better choice for that consideration.

No, Accessing the Request Context in a singleton API is disabled by default for performance.

Also .NET Core uses different classes for cookie so you’d need to override the CookieOptionsFilter() API instead.

1 Like