Cookies support in Streamlit!

Hi @Mohamed thanks for your quick reply. Indeed, the webauth_session cookie was set during the login thru Active Directory, not using Streamlit. Iā€™m talking about a deployed service.
Itā€™s also difficult to debug, because in local deployment there is no webauth_login, and all the cookies appear ā€¦ the problem is to get all the cookies in a deployed service.

If I run the script in this way:

cookies = cookie_manager.get_all()
cookies = cookie_manager.get_all()
st.write(cookies)

I get an error:

streamlit.errors.DuplicateWidgetID: There are multiple identical `st.extra_streamlit_components.CookieManager.cookie_manager` widgets with
`key='get_all'`.

To fix this, please make sure that the `key` argument is unique for
each `st.extra_streamlit_components.CookieManager.cookie_manager` you create.

so I run it in this way:

cookies = cookie_manager.get_all(key='1')
cookies = cookie_manager.get_all(key='2')
st.write(cookies)

But still I canā€™t see the required cookie containing the web authentication info, in the deployed service.
There is any limitation of this package related to the ā€œHttpOnlyā€ or ā€œSecureā€ cookie types?

1 Like

If you set a cookie through the console, such as document.cookie="new_cookie=new_value123" it will show up with cookies = cookie_manager.get_all(). The fact that your cookie was set with AD, make me think it was added with some restrictions, like it got be only accessed from certain domains. Other than that I doubt itā€™s a problem with the CookieManager.

1 Like

@Mohamed thanks for your answer. At the end I was able to get the cookie that I was looking for, using this package: from streamlit.server.server import Server

Then I compared the cookies coming from the headers (in the server) with the user cookies from your package to find a match of ā€œajs_anonymous_idā€. In that way I got the email of the user after decoding the cookie. And finally Iā€™m using the email to send back email notifications, but also to provide secure access to pages based on a table of privileges.

:grin:

2 Likes

Way to go @MarceTU !
If you donā€™t mind can you share a code snippet doing this process?

1 Like

Hi @Mohamed I will add some of the lines to run the code:
The only missing part here is to do a function to decrypt your cookies containing the email from the AUTH login server.

from streamlit.server.server import Server
import extra_streamlit_components as stx
from tornado import httputil #Handle Headers

def get_headers():
    # Hack to get the session object from Streamlit.
    headers=[]
    current_server = Server.get_current()
    if hasattr(current_server, '_session_infos'):
        # Streamlit < 0.56
        session_infos = Server.get_current()._session_infos.values()
    else:
        session_infos = Server.get_current()._session_info_by_id.values()
    # Multiple Session Objects?
    for session_info in session_infos:
        headers.append(session_info.ws.request.headers)
    return headers

def get_email():
  #here code your function to decrypt the cookies and get the email from the JSON body
  return email

def get_email_from_cookies():
    cookie_manager = get_manager()
    cookies = cookie_manager.get_all()
    headers = get_headers()
    for header in headers:
        for (k, v) in sorted(header.get_all()):
            if k == 'Cookie':
                temp_cookie = httputil.parse_cookie(v)
                try:
                    if cookies['ajs_anonymous_id'] in temp_cookie['ajs_anonymous_id']:
                        email = get_email(temp_cookie)
                        st.session_state['email'] = email
                except:
                    continue

#Finally just run:
get_email_from_cookies()
2 Likes

This is amazing @MarceTU . Thank you for posting this. Was looking into http cookies, or headers from Streamlit apps for ages! This just made my week! Cheers!! :beers:

1 Like

in cloud, I canā€™t seem to get any of the cookies to workā€¦

1 Like

Iā€™ve put the cookie manager example as a streamlit app and looks like you canā€™t set cookies on Cloud?

https://share.streamlit.io/averydata/streamlit-example

2 Likes

Well the definition of cloud is broad. But if you specifically mean share.streamlit.io, which its on device cookies are accessible by your application same to otherā€™s, then itā€™s a security issue. Which I am not sure if itā€™s allowed anymore to do on share.streamlit.io.
However if you host your Streamlit application on a domain/subdomain only accessible by your application then it shall not be an issue and you can easily set cookies using cookie manager.
TLDR; Itā€™s highly not advised to set user cookies on share.streamlit.io

1 Like

ah i see. Iā€™ll try again on GCP or Heroku or somethingā€¦thank you

1 Like

Iā€™m running into troubles with the CookieManager and getting cookies. I can successfully add cookies to the browser - I can see them in the developer tools. However, when I try getting the cookie, all I get is None. Thoughts, suggestions?

import extra_streamlit_components as stx
import streamlit as st


@st.cache(allow_output_mutation=True, suppress_st_warning=True)
def get_cookie_manager():
    return stx.CookieManager()


cookie_manager = get_cookie_manager()

cookie_name = "Cookie Test"
cookie_value = cookie_manager.get(cookie=cookie_name)
print(f"Cookie value: {cookie_value}")
if cookie_value is None:
    cookie_value = ""

with st.form(key="Cookie"):
    cookie_value = st.text_input(label="Cookie value:", value=cookie_value)

    submitted = st.form_submit_button("Submit")
    if submitted:
        print(f"Submitting: {cookie_value}")
        cookie_manager.set(cookie=cookie_name, val=cookie_value)
        print(f"After set: {cookie_manager.get(cookie=cookie_name)}")

1 Like

I figured out the problem. I had to change the cookies settings in Chrome to ā€œAllow all cookiesā€.

However, I still have a problem. When running my streamlit app I can refresh the browser and my cookie will be retrieved. However, if I stop and restart my streamlit app, the cookie isnā€™t found despite it showing up in the cookies in the developer tools.

1 Like

it is not working with on_click

1 Like

Hey there, thanks for making this. Iā€™m having some problems with st.error, st.status, or st.success alongside cookies; here is a minimum reproducible example with streamlit 1.10.0

import streamlit as st
import extra_streamlit_components as stx

@st.cache(allow_output_mutation=True)
def get_manager():
    return stx.CookieManager()

cookie_manager = get_manager()

button = st.button("Get cookies")
if button:
    st.subheader("All Cookies:")
    cookies = cookie_manager.get_all()
    st.write(cookies)
    st.success("This should show up for longer than a split second")

The green st.success box shows up for only a split second. Any help is much appreciated!

Edit: After posting this, I realized an example above worked fine using forms. As such, here is an extraordinarily hacky way to solve this bug.

import streamlit as st
import extra_streamlit_components as stx

@st.cache(allow_output_mutation=True)
def get_manager():
    return stx.CookieManager()

cookie_manager = get_manager()

with st.form(key="Cookie"):
    hide_streamlit_style = """
    <style>
    [data-testid="stForm"] {border: none; padding: 0;}
    </style>
    """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)
    submitted = st.form_submit_button("Get cookies")
    if submitted:
        st.subheader("All Cookies:")
        cookies = cookie_manager.get_all()
        st.write(cookies)
        st.success("This should show up for longer than a split second")
1 Like

Iā€™ve created a function that gets all cookies from the client, including HTTP-only cookies. The other functions posted by the users get all the cookies from all the sessions connected to the streamlit server. This is bad for security issues if you search for authentication cookies. Here I have a function that gets only the cookies for the client:

import re
from streamlit.server.server import Server
from streamlit.scriptrunner import add_script_run_ctx
def get_cookies() -> dict:
    session_id = add_script_run_ctx().streamlit_script_run_ctx.session_id
    session_info = Server.get_current()._get_session_info(session_id)
    header = session_info.ws.request.headers
    header = dict(header.get_all())
    cookies_str = header["Cookie"]
    results = re.findall(r"([\w]+)=([^;]+)", cookies_str)
    cookies = dict(results)
    return cookies
3 Likes

I cannot make it work,

I see cookies in the browser but none is returned when trying to get them

1 Like

This streamlit extension is awesome ! :v:t5:

1 Like

@Mohamed,

when I tried implementing in my app, it caused all sorts of unexpected behavior and was breaking my scripts. Turns out that calling cookie_manager causes the app.py script to run multiple times, and returns the cookies only on the last run. To test, I used session state to track the number of runs and the result:

@st.cache(allow_output_mutation=True)
def get_manager():
     return stx.CookieManager()

cookie_manager = get_manager()
cookies = cookie_manager.get_all()

if 'counter' not in st.session_state:
    st.session_state['counter'] = 0
    st.session_state['result'] = {}
st.session_state['counter'] = st.session_state['counter'] + 1
st.session_state['result'][st.session_state['counter']] = cookies
st.write(st.session_state['result'])

Result:

image

As you can see, the full script ran top to bottom 3 times before finally returning the cookies. That was the first run after starting the server. If I refresh the page, it will only run twice.

If I change ā€œcookies = cookie_manager.get_all()ā€ to "cookies = {ā€˜myā€™: ā€˜cookieā€™}, the script only runs once as expected:

image

Is this the intended behavior? Iā€™m guessing this is the reason many are having trouble getting it to work.

3 Likes

Same here. Cannot make it work. Cookies are there, but they are not returned. Occasionally it works.

2 Likes

see my post just above. when get_manager() is called, the script is trigger to run multiple times, it doesnā€™t return the cookies until the second or third pass. You need to write your script in such a way that it waits until the cookies are returned until proceeding.

2 Likes