coming here for some much needed help. We have quite the unique scenario with authentication using keycloak. Our requirement is as follows:
- "Parital" authenticated flow, where the backend creates a keycloak user, and returns the
access_token/refresh_tokenfor that respected user to our react front-end (useskeycloak-js) - Standard keycloak authenticated flow where the user authenticates via the keycloak login page and is returned to our application happily authenticated (this works fine and as expected!)
As you can imagine, point 1 is where our troubles are. Whenever I try to set the tokens manually for our keycloak instance and go to refresh the token, the call fails to keycloak because of a 400 bad request this is due to the request payload being undefined, though the instance properties (keycloak.accessToken, keycloak.refreshToken are populated):
grant_type: refresh_token
refresh_token: undefined
client_id: frontend
For implementation visuals, I've used @dasniko Niko Köbler Implementation as a starting point, but I simply just added a setter for the tokens:
import kc from 'keycloak';
const doLogin = kc.login;
const initKeycloak = (onAuthenticatedCallback: () => void) => {
kc.init({
onLoad: 'check-sso',
pkceMethod: 'S256',
enableLogging: true,
}).then((authenticated: boolean) => {
if (!authenticated) {
console.log('user is not authenticated..!');
}
onAuthenticatedCallback();
});
};
const setTokens = (access: string, refresh: string): void => {
kc.token = access;
kc.refreshToken = refresh;
};
const doLogout = kc.logout;
const getToken = () => kc.token;
const isLoggedIn = () => !!kc.token;
const updateToken = (successCallback: () => void) =>
kc.updateToken(5)
.then(successCallback)
.catch(doLogin);
I also have setup the token refresh implementation similarly:
axios.interceptors.request.use((config: any) => {
if (AuthService.isLoggedIn()) {
const cb = () => {
config.headers.Authorization = `Bearer ${AuthService.getToken()}`;
return Promise.resolve(config);
};
return AuthService.updateToken(cb);
}
return config;
});
Has anyone had any success attempting the above? Setting the keycloak tokens manually and not having the user login via keycloak first?