gpt4 book ai didi

reactjs - KeyCloak React refreshToken 过期 token

转载 作者:行者123 更新时间:2023-12-05 02:01:37 61 4
gpt4 key购买 nike

我想在我的客户端应用程序中实现授权,但我在使用 Keycloak 更新 React 应用程序中的 token 时遇到了问题。

App.js

import keycloak from "../../keycloak";

const App = () => {

const handleOnEvent = async (event,error) => {
if(event === 'onTokenExpired'){

keycloak.updateToken(300).then(
(response) => {
//I want to update my existing Token
alert("response: ", response )
})
.catch(error => {
console.log("error: ", error)
})
}
}


return (
<>
<ReactKeycloakProvider
authClient={keycloak}
onEvent={(event,error) => handleOnEvent(event,error)}>
<AppRouter/>
</ReactKeycloakProvider>
</>)
}
export default App;

标题

const Header = () => {
const {keycloak,initialized} = useKeycloak()

useEffect(() => {

if(keycloak.authenticated){
alert(JSON.stringify(keycloak))
localStorage.setItem("keycloakToken", keycloak.token); //set keycloak token to localStorag
localStorage.setItem("keycloakRefreshToken", keycloak.refreshToken); // set refresh token
setJWTToken(keycloak.token) //set to axios Authorization Bearer
}
},[keycloak.authenticated])

return(
<>
{
keycloak && !keycloak.authenticated && <UnloggedHeader keycloak={keycloak}/>
}
{
keycloak && keycloak.authenticated && <LoggedHeader keycloak={keycloak}/>
}
</>
)
}

export default Header

UnloggedHeader

function UnloggedHeader({keycloak}){

const signIn = () => {
keycloak.login()
}

return (
<div style={{minWidth: '1100px'}}>
<AppBar position="sticky" color='transparent'>
<Toolbar>
<Button onClick={signIn} variant="contained" color="primary">Login</Button>
<Typography variant="body1" component="h6">Unlogged</Typography>
</Toolbar>
</AppBar>
</div>
);
}

export default UnloggedHeader

记录头

function LoggedHeader({keycloak}){
let history = useHistory()
const [anchorEl, setAnchorEl] = React.useState(null);
const isMenuOpen = Boolean(anchorEl);
const handleProfileMenuOpen = (event) => {
setAnchorEl(event.currentTarget);
};
const [userInfo,setUserInfo] = useState()

useEffect(() => {
keycloak.loadUserInfo().then(userInfo => {
setUserInfo(userInfo)
localStorage.setItem("username", userInfo.preferred_username); // set username of user
})
},[])

const handleMenuClose = () => {
setAnchorEl(null);
};

const handleUserLogoutClick = () => {
keycloak.logout()
history.push("/")
}

return (
<div style={{minWidth: '1100px'}}>

<AppBar position="sticky" color='transparent'>
<Toolbar>

<Typography variant="body1" component="h6">{userInfo !== undefined ? userInfo.preferred_username : "EMPTY"}</Typography>
<ExpandMoreIcon/>
<Button onClick={handleUserLogoutClick} variant="contained" color="primary">Log out</Button>
</Toolbar>
</AppBar>
{renderMenu}
</div>
);
}

export default LoggedHeader

key 斗篷.js

import Keycloak from 'keycloak-js'

const keycloakConfig = {
url: 'http://10.192.168.72:8080/auth/',
realm: 'Realm12',
clientId: 'client',

}
const keycloak = new Keycloak(keycloakConfig);
export default keycloak

我需要向 ReactKeycloakProvider 提供什么才能在过期时获得新的 access_token?如何根据refreshToken值获取accessToken?我不知道哪个方法或端点会得到这个值。我在网络上找不到这种问题。

请帮帮我!

最佳答案

您可以在 Provider 上使用事件 onTokens

 <ReactKeycloakProvider
authClient={keycloak}
onTokens={({ token }) => {
// dispatch(setToken(token));
localStorage.setItem("keycloakToken", token);
}}
<AppRouter/>
</ReactKeycloakProvider>

要触发更新方法,您可以像这样在您的应用路由器中监听事件

export default function AppRouter() {
const { initialized, keycloak } = useKeycloak<KeycloakInstance>();

useEffect(() => {
if (keycloak && initialized) {
keycloak.onTokenExpired = () => keycloak.updateToken(600);
}
return () => {
if (keycloak) keycloak.onTokenExpired = () => {};
};
}, [initialized, keycloak]);

return (
<MyPreferedRouter>
<Switch />
</MyPreferedRouter>
);
}

正在开发@react-keycloak/ssr,我将此实现与 redux 一起使用,以在商店中拥有 token

不要忘记适配keycloak.updateToken(600);600 是你的 minValidity 的秒数

关于reactjs - KeyCloak React refreshToken 过期 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66365083/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com