Vue

How to integrate Single Sign-on with Vue and Django frameworks

The following guide provides a demo example to utilise SSO OpenID-Connect with Vue for IndustryApps. Additional adjustments may be required depending on your current configurations.

This Vue guide requires the following dependency installations via npm or yarn:

  • "keycloak-js"

  • "vue-router"

Once the required dependencies have been installed, a router folder should be created or a router addition should be implemented to include authentication directories.

index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import AuthorisedPage from '@/components/AuthorisedPage';

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/auth',
      name: 'AuthorisedPage',
      component: AuthorisedPage
    }
  ],
  mode:'history'
})

A model folder can be created in the client-side app project directory with keycloak configurations embedded with the required Industryapps Keycloak credentials which will then point to IndustryApps Keycloak resources.

Two files are to be added for this guide.

Config.js
export const CookieName = "Keycloak_Auth";
export const Config = {
    // URI is designated for development environment
    "url": "https://auth.uat.industryapps.net/auth/realms/IndustryApps",
    "realm": "IndustryApps",
    "clientId": "my-client-id"
}

The Functions.js file would contain functions which retrieve a user, create and utilise a Cookie for Keycloak which passes credentials.

Functions.js
export const getCurrentUser = () => {
    if (GetCookieValue("Keycloak_Auth")) {
      return true;
    }
    return false;
}
export const GetCookieValue = (cookiename) => {
    console.log(cookiename)
    let getCookie = document.cookie.match(new RegExp('(^| )' + cookiename + '=([^;]+)'));
    if (getCookie) {
        return getCookie[2];
    } else {
        return false;
    }
}
export const SetCookieValue = (cookiename, value) => {
    let date = new Date();
    let daysToExpire = 1;
    date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
    document.cookie = cookiename + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
    return true;
}
export const parseToken = function(token) {
    if(token === ""){
        return null;
    }
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var authObject = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(authObject);
};

Create a file named Home.vue in inside the Components directory, the file should contain Keycloak initialisation for a login, which then directs and decides on the appropriate flows for authentication. The home page would simply contain a button in this case. On click triggers an event for logging in through IndustryApps via Keycloak OpenID-Connect.

Home.vue
<template>
  <div class="mdWrapper">
      <button class="btn-normal" v-on:click="authenticateLogin">Login</button>
  </div>
</template>

<script>
  import Keycloak from 'keycloak-js'
  import { CookieName, Config } from '../model/Config';
  import { SetCookieValue } from '../model/Functions';
  // keycloak initialisation options
  let keycloak = Keycloak(Config);
  export default {
    name: 'Home',
    created: function(){
      keycloak.init({ flow: 'implicit', checkLoginIframe: false }).then((authenticated) => {
        try{
          if(!authenticated) {
            console.log("Not Authenticated");
            return false;
          } else {
            console.log("Authenticated");
          }
          SetCookieValue(CookieName, keycloak.token);
          this.$router.push({name: 'AuthorisedPage'})
        }
        catch(error){
          console.log("Authentication failed, Error: \n" + error);
        }
      })
    },
    methods: {
      authenticateLogin: function(){
        keycloak.login({ redirectUri: window.location.origin })
      }
    }
  }
</script>

Create a demo page for an authorised user named AuthorisedPage.vue

AuthorisedPage.vue
<template>
  <div class="wrapper">
      <h5>{{username}}</h5>
  </div>
</template>

<script>
  import { CookieName } from '../model/Config';
  import { parseToken, GetCookieValue } from '../model/Functions';
  export default {
    name: 'AuthorisedPage',
    created: function(){
      if(!GetCookieValue(CookieName)){
        this.$router.push({name: 'Home'});
      }
    },
    data: function(){
      return {
        username: parseToken(GetCookieValue(CookieName)).username
      }
    }
  }
</script>

Last updated