Add jwt token in the query params


A workaround to enhance the security when embedding a streamlit app.
User loginned in, and with the right permittion will be granted to visit the embedded page within an expiration period.


Code to generate the url to embed:

import jwt,time
def url_gen():
    # call this method to generate the url 
    payload = {
        "resource": "1", # app page id or other 
        "exp": round(time.time()) + (60 * 1) # 1 minute expiration
    token = jwt.encode(payload, ST_SECRET_KEY, algorithm="HS256")
    url = f'xxxx/?embedded=true&_jwt={token}' # embed this url
    return url

# django view for example
def embed_frame(request, required_perm=None):
    if required_perm and not request.user.has_perm(required_perm):
        return redirect("unauthorized")
    url = url_gen()
    context = {'embed_url': url}
    return render(request, 'pages/embed_page.html', context)

Streamlit app:

import streamlit as st
import jwt
import time

def auth():
    query = st.experimental_get_query_params()
    if token:=query.get('_kw'):
        payload = jwt.decode(token[0], ST_SECRET_KEY, algorithms=["HS256"])
        if payload['resource'] == '1' and payload['exp'] > round(time.time()):
            return True
    return False

def page():
    st.write("get it!")

if __name__ == '__main__':
    if auth():

Thanks @Andres-Peng for sharing this with the community! This would definitely come in handy.

Thank you, I made a tool that you can decode and encode jwt and share them using streamlit

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.