9951 explained code solutions for 126 technologies


reactjsHow can I implement Keycloak authentication with React.js?


  1. Install the Keycloak JavaScript adapter by running npm install keycloak-js in the terminal.

  2. Create a Keycloak instance in your React component's constructor method, passing it the initOptions object.

import Keycloak from 'keycloak-js';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { keycloak: null };
    const initOptions = {
      url: 'http://localhost:8080/auth',
      realm: 'master',
      clientId: 'my-react-app'
    };
    const keycloak = Keycloak(initOptions);
    this.state = { keycloak };
  }
  ...
}
  1. Initialize the Keycloak instance by calling keycloak.init() and passing it a success and error callback.
keycloak.init({ onLoad: 'login-required' }).success(authenticated => {
  this.setState({ authenticated });
}).error(err => {
  console.error(err);
});
  1. Wrap the component's render method with a call to keycloak.updateToken, which will ensure that the token is up to date.
render() {
  if (this.state.keycloak) {
    if (this.state.authenticated) {
      this.state.keycloak.updateToken(5).success(refreshed => {
        if (refreshed) {
          console.log('Token refreshed');
        } else {
          console.log('Token not refreshed');
        }
      }).error(err => console.error(err));
      ...
    }
  }
}
  1. Use the keycloak.token property to obtain the token and pass it with the request headers when making API calls.
axios.get('/api/data', {
  headers: {
    Authorization: 'Bearer ' + this.state.keycloak.token
  }
})
  1. Log out the user by calling keycloak.logout().
keycloak.logout()
  1. Finally, use the keycloak.login() method to redirect the user to the Keycloak login page.
keycloak.login()

Helpful links

Edit this code on GitHub