New component: Login authentication (Oauth) and localStorage access in Streamlit, synchronous communication

Hey folks,

I wanted to include a login with Google / Linkedin button on my Streamlit app. Tried many modules but didn’t get the experience I wanted.

So I’ve built a synchronous way to access localStorage from Streamlit using websockets (streamlit-ws-localstorage), please try it out.

I struggled for a couple of days with localStorage access (and authentication), and thought it would be easier to build a websocket based synchronous communication itself. The idea is inspired by how Streamlit uses websockets to communicate with the frontend. Hopefully this can be included into the main streamlit codebase itself.

The code is simple, just import the module and use it like this:

import streamlit as st
import uuid
from streamlit_ws_localstorage import injectWebsocketCode

# You can use my server for now, or run your own websocket server and auth redirect servers from here:

# Main call to the api, returns a communication object
conn = injectWebsocketCode(hostPort=HOST_PORT, uid=str(uuid.uuid1()))

st.write('setting into localStorage')
ret = conn.setLocalStorageVal(key='k1', val='v1')
st.write('ret: ' + ret)

st.write('getting from localStorage')
ret = conn.getLocalStorageVal(key='k1')
st.write('ret: ' + ret)

You can use the setLocalStorageVal and getLocalStorageVal functions to do some really interesting things like persist state across page reloads.


I’ve also built a Linkedin Oauth example using the same:

import uuid

import streamlit as st
import streamlit.components.v1 as components
from linkedin_v2 import linkedin
from streamlit_ws_localstorage import injectWebsocketCode
from streamlit_ws_localstorage.auth_redirect_server.auth_util import loginWithOAuthComponent

USER_PROFILE_PIC_KEY = '_user.profilePic'
USER_EMAIL_ADDRESS_KEY = '_user.emailAddress'
AUTH_CODE_KEY = '_linkedin.authCode'

# You can use my server for now, or run your own websocket server and auth redirect servers from here:

# Use this to avoid handling redirects in your app.
# Don't forget to register this as a redirect url in your linkedin app.

def getLinkedinOauth(uid):
    CLIENT_KEY = '<your client key>'
    CLIENT_SECRET = '<your client secret>'
    authentication = linkedin.LinkedInAuthentication(CLIENT_KEY, CLIENT_SECRET, REDIRECT_URL,
                                                     ['r_liteprofile', 'r_emailaddress'])

    # Set the state variable as the uid so the browser can receive the auth code corresponding to this request
    authentication.state = uid
    return authentication

def getLinkedinUserProfile(code):
    authObj = getLinkedinOauth('')
    authObj.authorization_code = code
    authToken = authObj.get_access_token()

    application = linkedin.LinkedInApplication(token=authToken)
    profile = application.get_profile()
    print('profile: ', profile)
    firstName, lastName, displayImage, id = profile['localizedFirstName'], profile['localizedLastName'], profile['profilePicture']['displayImage'], profile['id']

    # Get profile picture
    response = application.make_request('GET', '')
    json_response = response.json()
    print ('profile pic json_response: ', json_response)
    profilePic = json_response['profilePicture']['displayImage~']['elements'][2]['identifiers'][0]['identifier']

    # Get email
    response = application.make_request('GET', '*(handle~))')
    json_response = response.json()
    print ('email json_response: ', json_response)
    emailAddress = json_response['elements'][0]['handle~']['emailAddress']

    rsp = (firstName, lastName, displayImage, id, profilePic, emailAddress)
    print ('getLinkedinUserProfile: ', rsp)
    return rsp

def logoutFn():
    conn = injectWebsocketCode(hostPort=HOST_PORT, uid=str(uuid.uuid1()))
    conn.setLocalStorageVal(key=USER_PROFILE_PIC_KEY, val='')
    conn.setLocalStorageVal(key=USER_EMAIL_ADDRESS_KEY, val='')
    conn.setLocalStorageVal(key=AUTH_CODE_KEY, val='')
    st.write('Logged out, reloading the page')
    code = """<script>setTimeout(() => window.parent.location.reload(), 1000)</script>"""
    components.html(code, height=100)

def main():
    st.title('Login demo')

    uid = str(uuid.uuid1())
    conn = injectWebsocketCode(hostPort=HOST_PORT, uid=uid)
    print('conn: ', conn)

    emailAddress = conn.getLocalStorageVal(key=USER_EMAIL_ADDRESS_KEY)
    authCode = conn.getLocalStorageVal(key=AUTH_CODE_KEY)
    if authCode and not emailAddress:
        (firstName, lastName, displayImage, id, profilePic, emailAddress) = getLinkedinUserProfile(authCode)
        conn.setLocalStorageVal(key=USER_PROFILE_PIC_KEY, val=profilePic)
        conn.setLocalStorageVal(key=USER_EMAIL_ADDRESS_KEY, val=emailAddress)

    profilePic = conn.getLocalStorageVal(key=USER_PROFILE_PIC_KEY)
    emailAddress = conn.getLocalStorageVal(key=USER_EMAIL_ADDRESS_KEY)
    if emailAddress:
        st.write('Welcome ' + emailAddress)
        st.image(profilePic, width=200)
        st.button('Logout', on_click=logoutFn)
        uid = str(uuid.uuid1())
        authObj = getLinkedinOauth(uid)
        st.markdown('<a href="{}" target="_blank">Login with LinkedIn</a>'.format(authObj.authorization_url), unsafe_allow_html=True)
        loginWithOAuthComponent(HOST_PORT, uid, AUTH_CODE_KEY, reloadInSecs=6, height=40)


This shows a Login with LinkedIn link which opens the Linkedin auth page in a new tab, which upon success redirects to You can use this to avoid handling page redirects in your streamlit app.

If there’s interest, I can make simple button components for Linkedin, Google, Github to simplify this even further.


Here’s a video demo to see it working in action:


Installation: pip install streamlit-ws-localstorage
Repository: GitHub - gagangoku/streamlit-ws-localstorage: A simple synchronous way of accessing localStorage from your Streamlit app.
On pypi: streamlit-ws-localstorage · PyPI


Haven’t had time to try it out but thanks for the awesome contribution!
Saw you added it in a reply of the Tracker but whenever you can, definitely add it to the wiki in the top post, as not a lot of people scroll in the replies of the tracker :wink:

Keep up the great stuff!

1 Like

Thanks @andfanilo
Added to the Tracker !

1 Like