'PyQt5: How to set SameSite/Secure headers in QNetworkCookie

I have some Python code which sets a cookie like this:

loader = QtWebEngineWidgets.QWebEngineView()
profile = QtWebEngineWidgets.QWebEngineProfile("storage", loader)
cookie_store = profile.cookieStore()

with open('cookie.txt', 'rb') as f:
    contents = f.read()

cookie_store.setCookie(QNetworkCookie(contents))
webpage = QtWebEngineWidgets.QWebEnginePage(profile, loader)

Buit when I run the above code I get this error:

A cookie associated with a resource at was set with `SameSite=None` but without `Secure`

How can I fix that using PyQT5? How do I set SameSite=None and Secure using PyQt5?



Solution 1:[1]

Qt6 has a dedicated API for dealing with SameSite, but there's nothing equivalent in Qt5. So, since QWebEngineCookieStore only accepts QNetworkCookie objects, it will be necessary to construct them from the raw cookie data instead. This can be done quite easily using Python's http.cookie module (which will ensure everything is encoded properly):

from http.cookies import SimpleCookie

cookie = SimpleCookie()
cookie['name'] = 'value'
cookie['name']['samesite'] = None
cookie['name']['secure'] = True
contents = cookie.output().encode('ascii')

for qt_cookie in QtNetwork.QNetworkCookie.parseCookies(contents):
    print(qt_cookie.toRawForm())
    cookie_store.setCookie(qt_cookie)

Output:

b'Set-Cookie: name=value; secure; SameSite=None'

See e.g. MDN: SameSite cookies for an explanation of the various values that can be used with SameSite. It would appear that explictly setting SameSite=Lax may be a better default:

cookie = SimpleCookie()
cookie['name'] = 'value'
cookie['name']['samesite'] = 'Lax'
contents = cookie.output().encode('ascii')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ekhumoro