Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 9 Examples of "keycloak-js in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'keycloak-js' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

async function init() {
    let initOptions = await fetchAuthInfo();
    console.log(initOptions)
    if (initOptions.hasError) {
        console.warn("No Auth service available")
        ReactDOM.render(
            
                
            
            , document.getElementById('root')
        );
    } else {
        let keycloak = Keycloak(initOptions)
        keycloak.init({ onLoad: initOptions.onLoad }).success((auth) => {
            if (!auth) {
                window.location.reload();
            } else {
                console.info(`Dashboard - authenticated`);
            }
            ReactDOM.render(
                
                    
                
                , document.getElementById('root'));

            localStorage.setItem("cw-access-token", keycloak.token);
            localStorage.setItem("cw-refresh-token", keycloak.refreshToken);

            // Access token refresh
async logout (redirectUrl?: string) {
    let token = ConfigHelper.getFromSession(SessionStorageKeys.KeyCloakToken) || undefined
    if (token) {
      this.kc = Keycloak(ConfigHelper.getKeycloakConfigUrl())
      let kcOptions :KeycloakInitOptions = {
        onLoad: 'login-required',
        checkLoginIframe: false,
        timeSkew: 0,
        token,
        refreshToken: ConfigHelper.getFromSession(SessionStorageKeys.KeyCloakRefreshToken) || undefined,
        idToken: ConfigHelper.getFromSession(SessionStorageKeys.KeyCloakIdToken) || undefined
      }
      // Here we clear session storage, and add a flag in to prevent the app from
      // putting tokens back in from returning async calls  (see #2341)
      ConfigHelper.clearSession()
      // ConfigHelper.addToSession(SessionStorageKeys.PreventStorageSync, true)
      return new Promise((resolve, reject) => {
        this.kc && this.kc.init(kcOptions)
          .success(authenticated => {
            if (!authenticated) {
function init (config, watch, options) {
  const ctor = sanitizeConfig(config)
  const keycloak = Keycloak(ctor)

  watch.$once('ready', function (cb) {
    cb && cb()
  })

  keycloak.onReady = function (authenticated) {
    updateWatchVariables(authenticated)
    watch.ready = true
    typeof options.onReady === 'function' && watch.$emit('ready', options.onReady.bind(this, keycloak))
  }
  keycloak.onAuthSuccess = function () {
    // Check token validity every 10 seconds (10 000 ms) and, if necessary, update the token.
    // Refresh token if it's valid for less then 60 seconds
    const updateTokenInterval = setInterval(() => keycloak.updateToken(60).error(() => {
      keycloak.clearToken()
    }), 10000)
);

const app = (
  
    
      <div>
        
      </div>
    
  
);

const kc = new Keycloak('/keycloak.json');
kc.init({
  onLoad: 'check-sso',
  promiseType: 'native',
  silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html',
  pkceMethod: 'S256',
})
  .then(authenticated =&gt; {
    if (authenticated) {
      store.getState().keycloak = kc;
      ReactDOM.render(app, document.getElementById("app"));
    } else {
      console.warn("not authenticated!");
      kc.login();
    }
  });
created() {
      var keycloakAuth = new Keycloak("../keycloak.json");
      keycloakAuth.init({onLoad: 'login-required'}).success(function () {
        store.dispatch('checkUserIsLogin', keycloakAuth);
      }).error(function () {
        alert("failed to login");
      });
    },
    methods: {
init (idpHint: string, store: Store) {
    this.store = store
    this.cleanupSession()
    const token = ConfigHelper.getFromSession(SessionStorageKeys.KeyCloakToken) || undefined
    const keycloakConfig = ConfigHelper.getKeycloakConfigUrl()
    this.kc = Keycloak(keycloakConfig)
    const kcLogin = this.kc.login
    this.kc.login = (options?: KeycloakLoginOptions) =&gt; {
      if (options) {
        options.idpHint = idpHint
      }
      return kcLogin(options)
    }
    return this.kc.init({ token: token, onLoad: 'login-required' })
  }
VueKeyCloak.install = (Vue, options: Object = {
  keycloakOptions: {},
  keycloakInitOptions: {},
  refreshTime: 10
}) => {
  if (installed) return
  installed = true

  const keycloak: Object = Keycloak(options.keycloakOptions)

  const watch = new Vue({
    data () {
      return {
        ready: false,
        authenticated: false,
        user: null,
        token: null,
        resourceAccess: null
      }
    }
  })

  keycloak.init(options.keycloakInitOptions).success((isAuthenticated) => {
    updateWatchVariables(isAuthenticated).then(() => {
      watch.ready = true
import Keycloak from 'keycloak-js';
import React from 'react';

import { KeycloakProvider } from '../lib';

import { AppRouter } from './routes';

const keycloak = new Keycloak();

const keycloakProviderInitConfig = {
  onLoad: 'check-sso',
};

class PersistedApp extends React.PureComponent {
  onKeycloakEvent = (event, error) => {
    console.log('onKeycloakEvent', event, error);
  };

  onKeycloakTokens = tokens => {
    console.log('onKeycloakTokens', tokens);
  };

  render() {
    return (
import React from 'react';
import { withKeycloak as withKeycloakRaw } from 'react-keycloak';
import Keycloak from 'keycloak-js';

export const keycloak = new Keycloak(process.env.KEYCLOAK_JSON);
export const keycloakEnabled = !process.env.USE_MOCKS &amp;&amp; process.env.KEYCLOAK_ENABLED;
export const keycloakLogout = () =&gt; keycloak.logout();
keycloak.enabled = keycloakEnabled;

const keycloakDisabled = { enabled: false, authenticated: false };

const withKeycloakDisabled = WrappedComponent =&gt; (
  props =&gt; ());

export const withKeycloak = component =&gt; (keycloakEnabled
  ? withKeycloakRaw(component)
  : withKeycloakDisabled(component));

Is your System Free of Underlying Vulnerabilities?
Find Out Now