3

I want to implement authorization in my client-side application but I've got problem with update Token in React Application with Keycloak.

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;

Header

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

LoggedHeader

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

keycloak.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

What I need provide to ReactKeycloakProvider to get new access_token when was expired ? How based on refreshToken value get accessToken? I don't know which method or endpoint due to get this value. I can't find this kind of problem in network.

Please help me !

Dominic
  • 105
  • 1
  • 4
  • 13

3 Answers3

5

You can use event onTokens on Provider

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

And to trigger the update method, you can listen the event in your app router like this

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>
  );
}

Is working on @react-keycloak/ssr and i used this implementation with redux to have the token in the store

Don't forget to adapt keycloak.updateToken(600); 600 is number of seconds your minValidity

ValentinG
  • 106
  • 1
  • 3
0

I made some investigation in this point because I couldn't get new token by refresh token, this is what worked with me

I used Keycloak end point:

https://<yourAuthLink>/auth/realms/<relmName>/protocol/openid-connect/token

with headers object

headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}

and the body will be like that :

body: "client_id"=<clientId>&"grant_type"="refresh_token"&"refresh_token"=<refreshToken>&"client_secret"=<clientSecret>

this will return response which has access_token which you use as token and refresh_token to use it again before expiration time

it is useful link for this type of endpoint and headers

0

We use this flow

useEffect(() => {
    dispatch(keycloak.token);
    // and then save it to localStorage
}, [keycloak.token]);


useEffect(() => {
    // jast in case
    if(!initialized)
        return;

    if(!keycloak.authenticated)
        return;


    keycloak.onTokenExpired = () => {
        keycloak.updateToken(50);
    };
}, [keycloak.authenticated]);

But here I have a question: if the user sleep for a long time and then need to do some API request, so here I have to ask for refreshed token before request but useKeycloak hook doesn't work in this case

Pavel Zorin
  • 331
  • 6
  • 17