Okta登录重定向后authState未更新的React集成问题排查
问题:Okta与React集成后重定向回应用时authState为NULL,始终显示“Loading...”
我正尝试将Okta与React网页应用集成。应用可成功将用户路由至Okta登录页面,用户也能完成登录,但登录后Okta重定向回React应用时,authState未更新(读取时authState为NULL)。按我的代码实现,重定向后始终回到Home.js并显示“Loading...”文本,请问哪里存在遗漏?
示例代码实现
App.js
const oktaAuth = new OktaAuth({ issuer: 'https://{{ourDomain}}.com/oauth2/default', clientId: '{{ourValue}}', redirectUri: window.location.origin + '/login/callback', scopes: ["openid", "profile", "email"], pkce: true, }); <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}> <Switch> <Route path="/login/callback" component={LoginCallback} /> <Route path="/" component={Home} /> <SecureRoute path="/profile" component={Profile} /> </Switch> </Security>
Home.js
const { oktaAuth, authState } = useOktaAuth(); const login = async () => await oktaAuth.signInWithRedirect(); const logout = async () => oktaAuth.signOut(); const renderLogin = () => { if(!authState) { return <div>Loading...</div>; } if(!authState.isAuthenticated) { return ( <div> <p>Not Logged in yet</p> <button onClick={login}>Login</button> </div> ); } return ( <div style={{backgroundColor:'blue'}}> <p>Logged in!</p> <button onClick={logout}>Logout</button> </div> ); } return ( <div style={{height:'100%',justifyContent:'center', alignItems:'center',display:'flex'}}> {renderLogin()} </div> );
相关依赖版本
"@okta/okta-auth-js": "^7.2.0", "@okta/okta-react": "^6.7.0",
更新信息
从Okta托管登录重定向返回后,oktaAuth的状态显示:authState为null,isAuthenticated为false,但同时存在idToken等认证相关信息。
问题已解决
根本原因是使用了react-router-dom中的错误路由类型:
import { BrowserRouter as Router } from "react-router-dom"; // 正确使用此路由 // import { HashRouter as Router } from "react-router-dom"; // 此路由会导致问题,因为URL中会多出#符号,影响Okta回调后的状态同步
内容的提问来源于stack exchange,提问作者Tommy Leong
相关产品推荐
相关产品推荐

