我使用Keycloak在我的React应用程序中通过keycloak-js和@ react-keycloak / web libs对用户进行身份验证。
当我启动该应用程序时,它会将我重定向到keycloak登录页面,然后在输入登录名/密码后返回。
我得到令牌:访问,刷新等,并将其设置为cookie。
但是,然后,我猜想当访问令牌过期时,对我来说有些奇怪的事情开始了: chrome devtools network screenshot
应用程序获取令牌,但是从帐户页面(http:// localhost:8080 / auth / realms / my_pim / account),它获得401(未授权)状态。此后,它无法获取新令牌,但是以某种方式获取它,然后再次从帐户页面获取401。并且经历重定向的无限循环。 在keycloak服务器控制台中,我看到this。
我不知道该怎么办。
我的代码:
keycloak.ts
import keycloak, { KeycloakInstance } from 'keycloak-js';
const currentConfigName = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';
const keycloakClient: KeycloakInstance = keycloak(`/keycloak/config.${currentConfigName}.json`);
export default keycloakClient;
config.dev.json
{
"realm": "my_pim",
"auth-server-url": "http://localhost:8080/auth/",
"ssl-required": "external",
"resource": "pim_test",
"public-client": true,
"confidential-port": 0
}
App.tsx
import { ReactKeycloakProvider } from '@react-keycloak/web';
import keycloak from './keycloak';
import Cookies from 'universal-cookie';
const App = (): any => {
const dispatch = useDispatch();
const cookies = new Cookies();
const eventLogger = (event: unknown, error: unknown) => {
console.log('onKeycloakEvent', event, error);
};
const tokenLogger = (token: any) => {
if (token.token) {
console.log('onKeycloakTokens', token);
cookies.remove('user_token');
cookies.set('user_token', token.token, { path: '/' });
dispatch(actions.setAuth(true));
}
};
return (
<BrowserRouter>
<ReactKeycloakProvider
initOptions={{ onLoad: 'login-required' }}
onTokens={tokenLogger}
onEvent={eventLogger}
authClient={keycloak}>
<div className="app-wrapper">
// my components here
</div>
</ReactKeycloakProvider>
</BrowserRouter>
);
};
export default App;