首页 > 解决方案 > 避免每次刷新页面时keycloak回调过程

问题描述

我在我的反应应用程序中使用了 keycloak 作为身份提供者。我已经使用 npm 在我的反应应用程序中安装了 keycloak 反应依赖项。

以下是依赖的 keycloak react npm 模块与版本:

“@react-keycloak/web”:“2.1.4”,
“keycloak-js”:“^11.0.2”,

我提供了如下 keycloak 配置:

const keycloak = new Keycloak({
  realm: "temp-local",
  url: " http://localhost:8090/auth/",
  clientId: "temp-local-client"
});

每次我刷新页面时,它都会使用查询参数statesession_statecode再次刷新(使用回调 url) 。

例如:当我转到页面时:http://localhost:8080/test 它会去那里,但它会再次使用以下 url 刷新页面。

示例网址:http://localhost:8080/test# state =45ert45-edac92ddbf2a& session_state =45ga97bbfb4-f080cvb65e59b&代码=1a1a-4e6e-3fg578-4fg10b-bbafg8-652fg6c44727a4

如何避免密钥斗篷刷新?任何人都可以对此有任何想法吗?

标签: javascriptreactjsconfigurationkeycloak

解决方案


有同样的问题,对我来说我是这样解决的:

在主要组件中:

const App = () => {
    //here i'm using redux, btw i'm initializing this auth component
    useEffect(() => auth.init(store.dispatch), [])

身份验证组件:

import Keycloak from 'keycloak-js';
const keycloak = Keycloak('/keycloak.json');
import axios from 'axios'
import { LocalStore } from '../utils/local_store.js'

const store_token = (token) => {
    axios.defaults.headers.Authorization = `Bearer ${token}`;
    LocalStore.set('token', token);
}

const auth = {
    init(dispatch) {


        keycloak.init({ onLoad: 'login-required', checkLoginIframe: false, }).then(() => {
            store_token(keycloak.token)
            dispatch(authenticateResponse(keycloak.token)).then(
                () => {
                   //auth logic
                }
            );

            //this is my fix
            setInterval(() => {
                keycloak.updateToken(70).then((refreshed) => {
                    if (refreshed) {
                        store_token(keycloak.token)
                        console.debug('Token refreshed');
                    } else {
                        console.warn('Token not refreshed');
                    }
                }).catch(() => {
                    console.error('Failed to refresh token');
                });
            }, 50000)

        }).catch(() => {
            console.error('Auth failed');
        });
    },
    keycloak() {
        return keycloak;
    }
}


export default auth;

推荐阅读