0.1.2 • Published 2 years ago

nxp-keycloak-plugin v0.1.2

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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)
  })
}