Integration of the keycloak with react JS
Pre-requisites: Node module and keycloak installed on the machine.
Note : Make sure both don’t share the default port number 8080
Step 1 : Go to your react project folder and install node module packages by
npm install
Step 2 : Install keycloak packages from npm
npm install keycloak-js—save –dev
Step 3 : add the below code to your main js file
Import the keycloak js to the js file
import Keycloak from “keycloak-js”;
const kc = Keycloak(‘/keycloak.json’);
kc.init({onLoad: ‘check-sso’}).success(authenticated => {
if (authenticated) {
store.getState().keycloak = kc;
setInterval(() => {
kc.updateToken(10).error(() => kc.logout());
}, 10000);
ReactDOM.render(app, document.getElementById(“app”));
} else {
// show possibly other page here…
kc.login();
}
});
axios.interceptors.request.use(config => {
config.headers = {
‘Content-Type’: ‘application/json’,
Accept: ‘application/json’,
Authorization: ‘Bearer ‘ + kc.token
};
return config;
});
Step 4: install the latest keycloak and configure the keycloak
Keep the keyclok.json file in the js file directory of react js
Step 5: Verify the tocken which is append by keycloak redirect url .
Step 6 : run node module
Npm start
…………………………………………………………………………………………………………………………………
Configure the Keycloak realm ::
Create New realm : Demo
Create new client : demo
Configure the urls :: Root URL http://localhost:8691/index.html
* Valid Redirect URIs :: http://localhost:8691/*
Note : this url end must have * else it won’t redirect .
Base URL :: http://localhost:8691/index.html
Web Origins :: http://localhost:8691
- Add the User Roles to the clients
- Go to the installation and select keycloak OIDC json and get the JSOn , it look like
{
“realm”: “demo”,
“auth-server-url”: “http://localhost:8080/auth”,
“ssl-required”: “external”,
“resource”: “demo”,
“public-client”: true,
“use-resource-role-mappings”: true,
“disable-trust-manager”: true,
“allow-any-hostname”: true
}
- Copy to your project js or root folder with extension .json
- Add the users and assign the same role as clients
you are all set to run the react keycloak integration
Use of Axios :
Axios Component for React with child function callback. This is intended to allow in render async requests.
Features
- Component driven
- Child function callback (error, response, isLoading) => { }
- Auto cancel previous requests
- Debounce to prevent rapid calls.
- Request only invoked on prop change and isReady state.
- Callback props for onSuccess, onError, and onLoading
- Supports custom axios instances through props or a <AxiosProvider … >
Installing
Using npm:
$ npm install react-axios
Also install the required peer dependancies if you have not already done so:
$ npm install axios
$ npm install react
$ npm install prop-types
Filed under: Keycloak, React JS | Tagged: keycloak integration with react, keycloak-react | Leave a comment »