skip to Main Content

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


  1. 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 a clientSecret option AFAICT so not sure where you go that from (it’s a bit confusing because clientSecret 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 to keycloak.init() and remove the clientSecret option.

    Login or Signup to reply.
  2. 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 :

    1. Creation new realm
    2. Setting home url, base url, redirect url, web origins
    3. Setting "authentication flow overrides" in advanced tab of client, "Browser Flow" to browser and "Direct Grant Flow" to "direct grant"
    4. Create User and Role, assign Role to User and make sure role should contain client scope and client scope should include web origin so that you will not face issue with CORS and tokens
      and then you can check
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search