Avoid keycloak callback process every time when refreshing page

泄露秘密 提交于 2021-01-28 11:30:26

问题


I have used keycloak as a identity provider in my react application. I have installed keycloak react dependency in my react application using npm.

Below are the dependent keycloak react npm modules with version :

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

I have provided keycloak configurations as below :

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

Everytime when I refresh the page it will refresh again (with callback url) with query parameters state, session_state and code.

For example : When I go to the page : http://localhost:8080/test it will go there but again it will refresh the page with below url.

Sample url : http://localhost:8080/test#state=45ert45-edac92ddbf2a&session_state=45ga97bbfb4-f080cvb65e59b&code=1a1a-4e6e-3fg578-4fg10b-bbafg8-652fg6c44727a4

How to avoid that keycloak refresh? Can anyone have any idea on this?


回答1:


Had the same problem, for me i fixed like this:

in the main component:

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

the auth component:

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;


来源:https://stackoverflow.com/questions/65182935/avoid-keycloak-callback-process-every-time-when-refreshing-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!