npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

keycloak-js-util

v1.3.1

Published

Simplified access to keycloak-js

Downloads

13

Readme

keycloack-js-util

User frindly js library for authentication with Keycloak.

npm install keycloak-js-util

⭐️ Features

  • async library
  • basic login
  • easy to use async fetch wrappers that add authorization bearer token header
  • tested
  • Correct keyclock CORS and CSP(content security policy) configuration: https://github.com/shimondoodkin/keycloak-js-util/tree/master/example/config
  • Correct krakend (CORS) configuration: https://github.com/shimondoodkin/keycloak-js-util/blob/master/example/krakend.json

✅ running the example:

there is an example at https://github.com/shimondoodkin/keycloak-js-util/tree/master/example

  • you need to have doker installed.
  • git clone https://github.com/shimondoodkin/keycloak-js-util.git
  • in the example folder:
  • run all bat files:
    • run-krakend-docker.bat
    • run-keycloack-docker.bat
    • run-server.bat or python3 server.py or node server.js
    • run-vue-app.bat or enter folder: example\vue-app and run: npm run dev
  • configure keycloak like described in https://github.com/shimondoodkin/keycloak-js-util/tree/master/example/config ( describes how to overcome CORS and content security policy issues with keycloak) open key cloak at http://localhost:8080
  • try login to http://localhost:8081

Example 1


import {authInit,setOnRefreshTokenError,getKeycloak} from 'keycloak-js-util'

try {
  await authInit({ 
    url: 'http://localhost:8080/', 
    realm: 'keycloak-demo', 
    clientId: 'app-vue',
    //  onLoad:'login-required',
    onLoad: 'check-sso',
    silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html' 
  });

  //optionally respont to authenticaation right away with  login
  if(!getKeycloak().authenticated) 
  {
    // if authentication is failed,  try to re-authenticate. don't load the application.
    //  
    //   if onLoad:'login-required' is used then maybe refresh window.location.reload().
    //   or call getKeycloak().login() 

    console.log('not authorized')
    getKeycloak().login()    

  }
  else
  {
    // authenticated successfuly, load the application

    // add handler for refresh token error
    setOnRefreshTokenError((error) => { 
      // for example:
      // alert("dispaly message you have been disconnected.\n"+error.message);
      // window.location.reload();
    });

    // load application here
    // for example
    //  createApp(App).mount('#app');
  }
}
catch(e)
{
  console.error(e)
  // display error message
  // for example
  //  createApp(ErrorPage,{
  //    title: 'Application initialization error:',
  //    message: e.message,
  //    returnUrl: '/',
  //  }).mount('#app');
}

Silent SSO: To enable the silent check-sso, you have to provide a silentCheckSsoRedirectUri attribute in the init method. This URI needs to be a valid endpoint in the application (and of course it must be configured as a valid redirect for the client in the Keycloak Admin Console):

  const authenticated=await authInit({
        url: 'http://localhost:8080/',
        realm: 'keycloak-demo', clientId: 'app-vue',
        onLoad: 'check-sso',
        silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html' });

The page at the silent check-sso redirect uri is loaded in the iframe after successfully checking your authentication state and retrieving the tokens from the Keycloak server. It has no other task than sending the received tokens to the main application and should only look like this:

<html>
<body>
    <script>
        parent.postMessage(location.href, location.origin)
    </script>
</body>
</html>

Example 2



import {authFetchText,authFetchJSON,authFetch} from 'keycloak-js-util'

const data = await authFetchText('http://localhost:8082/v1/test.txt')
const data = await authFetchJSON('http://localhost:8082/v1/test.json')
const data = await authFetchBlob('http://localhost:8082/v1/test.jpg')


const response = await authFetch('http://localhost:8082/v1/test')
if(!response.ok)
  throw new Error('Http status code='+response.code)
const data = await response.json()

in keycloak there are many useful functions, see documentation:

// keycloak-js:
//   reference: https://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter
//   source code of keycloak-js: https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-js
//   npm pakcage: https://www.npmjs.com/package/keycloak-js

list of methods of keycloak instance:

  keycloak.init(options) // redirects if onLoad:'login-required'
  keycloak.login(options) // redirects
  keycloak.createLoginUrl(options)
  keycloak.logout(options) // redirects
  keycloak.createLogoutUrl(options)
  keycloak.register(options) // redirects
  keycloak.createRegisterUrl(options)
  keycloak.accountManagement() // redirects
  keycloak.createAccountUrl(options)
  keycloak.hasRealmRole(role)
  keycloak.hasResourceRole(role, resource)
  keycloak.loadUserProfile()
  keycloak.isTokenExpired(minValidity)
  keycloak.updateToken(minValidity)
  keycloak.clearToken()

list of properties of keycloak instance:

  keycloak.authenticated
  keycloak.token
  keycloak.tokenParsed
  keycloak.subject
  keycloak.idToken
  keycloak.idTokenParsed
  keycloak.realmAccess
  keycloak.resourceAccess
  keycloak.refreshToken
  keycloak.refreshTokenParsed
  keycloak.timeSkew
  keycloak.responseMode
  keycloak.flow
  keycloak.adapter
  keycloak.responseType

Written by Shimon Doodkin