AMendis
AMendis

Reputation: 1574

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?

Upvotes: 1

Views: 410

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

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')

Upvotes: 1

Related Questions