Python Streamlit Azure Web App中获取Azure ID Token遇Cookie获取难题
问题分析与解决方案
你遇到的核心问题是AppServiceAppAuth cookie带有HttpOnly属性,这个属性会阻止前端JavaScript(包括Streamlit的前端CookieManager依赖的API)读取该cookie,所以你用cookie_manager.get_all()拿不到它——浏览器开发者工具能看到是因为工具不受HttpOnly限制,而前端JS不行。
你的实现方向有偏差,正确的做法是从服务器端获取认证信息,而不是前端:
方案1:直接读取Azure注入的请求头
Azure App Service的认证模块会自动把用户的认证信息注入到请求的HTTP头中,不需要调用/.auth/me就能拿到id_token和用户信息:
import streamlit as st def get_azure_auth_details(): # 从Streamlit的请求上下文获取HTTP头 request_headers = st.context.request.headers # 提取Azure注入的认证字段 return { "id_token": request_headers.get("X-MS-TOKEN-ID-TOKEN"), "user_name": request_headers.get("X-MS-CLIENT-PRINCIPAL-NAME"), "user_id": request_headers.get("X-MS-CLIENT-PRINCIPAL-ID") } auth_details = get_azure_auth_details() st.subheader("Azure认证信息") st.write(auth_details)
方案2:服务器端调用/.auth/me端点
如果必须调用/.auth/me,要在Streamlit的后端代码中发起请求——服务器端可以拿到所有cookie(包括HttpOnly的),因为浏览器会把所有相关cookie传递给Web App服务器:
import streamlit as st import requests def fetch_auth_me_data(): # 从请求上下文获取所有cookie(包括HttpOnly的AppServiceAppAuth) request_cookies = st.context.request.cookies # 服务器端发起请求到/.auth/me,部署在Azure上时用相对路径即可 response = requests.get("/.auth/me", cookies=request_cookies) if response.ok: return response.json() return {"错误": f"请求失败,状态码:{response.status_code}"} auth_me_data = fetch_auth_me_data() st.subheader("从/.auth/me获取的认证数据") st.write(auth_me_data)
为什么之前的方式无效?
streamlit-cookie-manager依赖浏览器的Document.cookie API读取cookie,但HttpOnly属性的cookie会被浏览器禁止JS访问,这是安全设计——防止XSS攻击窃取敏感认证cookie,所以前端无法读取,只能通过服务器端获取。
内容的提问来源于stack exchange,提问作者ddexter
相关产品推荐
相关产品推荐

