如何在React前端获取Python认证系统的登录用户名?
问题:React前端无法显示登录用户名(OAuth2非JWT场景)
我有一个Python登录认证项目,已经和React前端对接完成,前端能根据登录状态展示不同内容,但没法显示用户登录时使用的用户名。
React配置
clientId: "my client id from the db", authorizationEndpoint: "the OAuth authorization endpoint", tokenEndpoint: "The token endpoint", redirectUri: "my path to react after authorization",
使用依赖
使用的是react-oauth2-code-pkce npm包。
不适用的配置项
因为我的令牌不是JWT,所以以下配置和属性不适用:
// An object with all the properties encoded in the token (username, email, etc) tokenData?: TTokenData
// Whether or not to decode the access token (should be set to 'false' if the access token is not a JWT (e.g. from Github)) // If `false`, 'tokenData' will be 'undefined' from the <AuthContext> decodeToken?: boolean // default: true
登录流程
- 用户在React页面点击
Log In按钮; - 跳转至Python端的登录表单;
- 用户输入用户名和密码;
- 在Python端点击
authorize完成授权; - 跳转回React页面,展示授权前无法查看的内容。
现需实现在React前端显示该用户名,恳请指导。
解决方案思路
既然令牌不是JWT,无法直接解码获取用户名,推荐两种可行方案:
方案1:授权回调时携带用户名到前端
修改Python端的OAuth2授权逻辑,完成授权跳转回React的redirectUri时,通过查询参数携带用户名,示例跳转链接:
https://your-react-app.com/callback?code=xxx&username=johndoe
在React的回调页面,读取URL的username参数,将其存入localStorage或全局状态(如Context、Redux),后续即可在需要的页面展示。
安全优化:若担心用户名暴露,可仅返回授权码,前端拿到后调用Python接口验证令牌并获取用户名。
方案2:新增用户信息接口,前端用令牌请求
在Python后端新增接口(如/api/user/info),该接口要求前端携带授权后的access token,验证令牌有效性后返回当前用户的用户名信息。
React端登录成功拿到access token后,调用该接口:
import { useAuth } from 'react-oauth2-code-pkce'; const UserInfo = () => { const { accessToken } = useAuth(); useEffect(() => { if (accessToken) { fetch('/api/user/info', { headers: { 'Authorization': `Bearer ${accessToken}` } }) .then(res => res.json()) .then(data => { localStorage.setItem('username', data.username); }); } }, [accessToken]); return <div>用户名:{localStorage.getItem('username')}</div>; };
补充:react-oauth2-code-pkce配置调整
记得在AuthProvider中设置decodeToken={false},避免不必要的解码报错:
import { AuthProvider } from 'react-oauth2-code-pkce'; <AuthProvider clientId="your-client-id" authorizationEndpoint="your-auth-endpoint" tokenEndpoint="your-token-endpoint" redirectUri="your-redirect-uri" decodeToken={false} > {/* 应用组件 */} </AuthProvider>
内容的提问来源于stack exchange,提问作者r j
相关产品推荐
相关产品推荐

