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

nxp-keycloak-plugin

v0.1.2

Published

Plugin Keycloak for vue js application

Downloads

4

Readme

Introduction

This document's purpose is to explain how to effectively use the nxp-keycloak-plugin plugin in order to secure your vuejs application with Keycloak.

Setup

install the component with the following command:

npm install --save nxp-keycloak-plugin

Then import it in your application :

import VueKeycloakJs from 'nxp-keycloak-plugin'

and use it in main.js as the following:

...
Vue.use(VueKeycloakJs, {
  init: {
    onLoad: 'check-sso'
  },
  config: {
    url: 'https://mykeycloak-server.com/auth',
    clientId: 'MyClientId',
    realm: 'MyRealm'
  },
  onReady: (keycloak) => {
    new Vue({
      router,
      render: h => h(App)
    }).$mount('#app')
  }
})

Usage

The Library inject a variable named keycloak. This object provide the following methods & properties :

{
  ready: Boolean,              // Flag indicating whether Keycloak has initialised and is ready
  authenticated: Boolean,
  userName: String,            // Username from Keycloak. Collected from tokenParsed['preferred_username']
  fullName: String,            // Full name from Keycloak. Collected from tokenParsed['name']
  login: Function,             // [Keycloak] login function
  loginFn: Function,           // Alias for login
  logoutFn: Function,          // Keycloak logout function
  checkTokenForUpdate: Function, // check token validity within minValidity param and update it if necessary
  createLoginUrl: Function,    // Keycloak createLoginUrl function
  createLogoutUrl: Function,   // Keycloak createLogoutUrl function
  createRegisterUrl: Function, // Keycloak createRegisterUrl function
  register: Function,          // Keycloak register function
  accountManagement: Function, // Keycloak accountManagement function
  createAccountUrl: Function,  // Keycloak createAccountUrl function
  loadUserProfile: Function,   // Keycloak loadUserProfile function
  loadUserInfo: Function,      // Keycloak loadUserInfo function
  subject: String,             // The user id
  idToken: String,             // The base64 encoded ID token.
  idTokenParsed: Object,       // The parsed id token as a JavaScript object.
  realmAccess: Object,         // The realm roles associated with the token.
  resourceAccess: Object,      // The resource roles associated with the token.
  refreshToken: String,        // The base64 encoded refresh token that can be used to retrieve a new token.
  refreshTokenParsed: Object,  // The parsed refresh token as a JavaScript object.
  timeSkew: Number,            // The estimated time difference between the browser time and the Keycloak server in seconds. This value is just an estimation, but is accurate enough when determining if a token is expired or not.
  responseMode: String,        // Response mode passed in init (default value is fragment).
  responseType: String,        // Response type sent to Keycloak with login requests. This is determined based on the flow value used during initialization, but can be overridden by setting this value.
  hasRealmRole: Function,      // Keycloak hasRealmRole function
  hasResourceRole: Function,   // Keycloak hasResourceRole function
  token: String,               // The base64 encoded token that can be sent in the Authorization header in requests to services
  tokenParsed: String          // The parsed token as a JavaScript object
}

In addition to that, nxp-keycloak-plugin plugin emits the following events to be intercepted in your application.

  • onNotAuthenticated: "keycloak-Not-Authenticated",
  • onSessionExpired: "keycloak-Session-Exprired",

In order to intercept an event, you can achieve that by :


created() {
    Vue.prototype.$keycloak.keycloakevents.$on(Vue.prototype.$keycloak.eventTypes.onSessionExpired,, () => {
       //do your stuff
    });
    Vue.prototype.$keycloak.keycloakevents.$on(Vue.prototype.$keycloak.eventTypes.onSessionExpired,, () => {
       //do your stuff
    });
  }

Secure paths

to explain the process, you may follow this example.

Let's assume we have 4 routes ('/', 'request','admin', 'user')

  • '/' is public
  • 'request' and user needs the user to be authenticated
  • 'admin ensure that you have admin role to access it
const routes = [
  { path: "/", name: "Hello", component: Hello},
  {
    path: "/request",
    name: "Request",
    component: Request,
    meta: { requiresAuth: true }
  },
  {
    path: "/admin",
    name: "Admin",
    component: Admin,
    meta: { requiresAuth: true, role: "admin" }
  },
  { path: "/user",
    name: "User",
    component: User,
    meta: { requiresAuth: true } 
   }
];
...

meta attribute specify whether this resource require authentication or not and which role is secured by.

So, to secure your paths (menu items), call the method secureRouter of vKey as the following in your router

    ...
   router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (router.app.$keycloak.authenticated) {
      if(to.meta.role){
        if(router.app.$keycloak.hasRealmRole(to.meta.role)){
          next()
        }else{
          //Tell connected user that he is unauthorized to visit this path
        }
      }else{
        next();
      }
     
    } else {
      const loginUrl = router.app.$keycloak.createLoginUrl()
      window.location.replace(loginUrl)
    }
  } else {
    next()
  }
})

In conjunction with the above, you might find it useful to intercept e.g. axios and set the token on each request:

import axios from "axios";
import Vue from "vue";

export default function setup() {
    axios.interceptors.request.use(async config => {
    await Vue.prototype.$keycloak.checkTokenForUpdate(30)
    config.headers.Authorization = `Bearer ${Vue.prototype.$keycloak.token}`
    return config
  }, error => {
    return Promise.reject(error)
  })
}