I am trying to implement a basic Keycloak authentication on my react website.
During the authentication init, authentication is failing and on the react server side I am getting the error invalid_client_credentials.
Once I goto my react website I am prompted with a Keycloak login page, where I enter username and password and I login successfully. But does not execute any part of the code after init.
import React from 'react';
import ReactDOM from 'react-dom';
import Keycloak from 'keycloak-js';
const keycloak = Keycloak({
url: 'http://localhost:8080/',
realm: 'reactrealm',
clientId: 'reactclient',
clientSecret: 'xvtYZ5P7ybsjvmAO4YY2Eu6NifsePLBg'
});
keycloak.init({ onLoad: 'login-required' }).then((authenticated) => {
if (authenticated) {
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
} else {
ReactDOM.render(
<h1>Goodbye, world!</h1>,
document.getElementById('root')
);
}
});
2
Answers
If you have a backend API in your react app you should use code flow, and the client secret belongs in your API code not your react front end code. If you don’t have a backend you have to use implicit flow. In this case there is no client secret – there is no point in having one because there is no way the client (your React in-browser code) can’t keep it a secret.
keycloak-js@latest
(currently v21.0.1) doesn’t even support aclientSecret
option AFAICT so not sure where you go that from (it’s a bit confusing becauseclientSecret
is mentioned in the [typings][1] but never actually used in the [code][2]. Maybe it used to be supported a few versions ago?).Assuming you don’t have a backend and want to use implicit flow. set "Client authentication" option to OFF and enable implicit flow for the client in the keycloak admin console. Then pass
flow: "implicit"
option tokeycloak.init()
and remove theclientSecret
option.Generally we get this error in new keycloak UI when we enable "client authentication" in "capability config" of client. Please make sure it is disabled and standard flow and direct grant are only ticked.
Following steps may help you for keycloak latest UI :
and then you can check