Python版Shiny中SSO认证后如何获取当前会话详情?
问题描述
我正在开发一款集成SSO认证的应用,认证完成后可通过request.session.get('user')获取用户信息。
- 最初在Shiny的server函数外部定义了
user_details = {}变量并赋值会话信息,功能虽正常,但存在服务器会话数据残留问题——我完成SSO登录后,朋友登录网页时看到了我的名字。 - 经调研得知需将
user_details变量移入server函数内,但移入后无法为该变量赋值会话用户信息。
代码示例
def server(input, output, session): user_details = session.user print(user_details) shiny_app = App(app_ui, server) #----------------------------------------------------------------------END OF SHINY----------------------------------------------------- #---------------------------------------------------------------------START OF SSO------------------------------------------------------- config = Config('.env') oauth = OAuth() CONF_URL = #config url oauth.register( name = "app", server_metadata_url = CONF_URL, client_id = config.get('client_id'), client_secret = config.get('client_secret'), client_kwargs={ 'scope': 'openid email' } ) random_secret_key = secrets.token_urlsafe(32) class AuthMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): # Check if the user is authenticated user = request.session.get("user") # List of paths that require authentication protected_paths = ["/dash", "/dash/"] # If the path is protected and the user is not authenticated if request.url.path in protected_paths and not user: #Redirect to the login page or SSO login flow return RedirectResponse(url="/login") # Proceed with the next middleware or route handler response = await call_next(request) return response async def homepage(request): global user_details user = request.session.get('user') if user: return RedirectResponse(url='/dash') #return JSONResponse(user) return RedirectResponse(url = '/login') async def login(request): redirect_uri = request.url_for('auth') return await oauth.app.authorize_redirect(request, redirect_uri) async def auth(request): token = await oauth.app.authorize_access_token(request) user = token.get('userinfo') if user: request.session['user'] = user return RedirectResponse(url='/') async def healthcheck(request): return JSONResponse({"Status" : "running"}, headers = {"Cache-Control" : "max-age=0, no-cache, no-store"}) routes = [ Route('/health/ping', healthcheck), Route('/', homepage), Route('/login', login), Route('/auth', auth), Mount('/Static', StaticFiles(directory = 'www'), name = 'static'), Mount('/dash', app = shiny_app) ] app = Starlette(routes=routes) app.add_middleware(AuthMiddleware) app.add_middleware(SessionMiddleware, secret_key = random_secret_key)
已尝试的方法
尝试了文档中提及的session.get_current_session()方法,但系统提示“AppSession对象没有get_current_session()属性”。
内容的提问来源于stack exchange,提问作者Mathew Varkey
相关产品推荐
相关产品推荐

