Retrieving Instance from main.js through a logout button in vue.js

Using keycloak-js for authenticating my vue.js application, I have implemented the following code in my main.js file. This snippet was taken from :

import { store } from "./store/store";

let keycloak = Keycloak(initOptions);

keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => {
  if (!auth) {
    window.location.reload();
  } else {
    console.log("Authenticated");
    new Vue({
      vuetify, router, store,
      render: h => h(App,  { props: { keycloak: keycloak } })
    }).$mount('#app')

  }

  const decoded = VueJwtDecode.decode(keycloak.token)
  const roles = decoded.realm_access.roles
  store.commit("storeRoles", roles)

//Token Refresh
  setInterval(() => {
    if(store.state.userData.logged_out) { ### done in vuex
      keycloak.logout()
    } else {
      keycloak.updateToken(70).then((refreshed) => {
        if (refreshed) {
          console.log('Token refreshed' + refreshed);
        } else {
          console.log('Token not refreshed, valid for '
            + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
        }
      }).catch(() => {
        console.log('Failed to refresh token');
      });
    }
  }, 2000)

}).catch(() => {
  console.log("Authenticated Failed");
});

In order to handle this process through a button click, I'm currently committing a mutation in my Vuex store.

if(store.state.userData.logged_out) { ### done in vuex
    keycloak.logout()
}

## Triggered by clicking a button in my view
this.$store.commit("logout", true)

The current approach feels a bit cumbersome as there is a 2-second delay before the user is logged out. Is there a more direct way to access the keycloak instance from a component?

Answer №1

After receiving a helpful hint from @augstin gorni, I successfully resolved the issue by including the keycloak instance in the Vue.prototype.

If you want to learn more about adding instance properties in Vue.js, check out this link: https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html

let keycloak = Keycloak(initOptions);
Vue.prototype.$keycloak = keycloak

This solution now allows for global accessibility of the keycloak instance.

logout() {
  this.$keycloak.logout()
}

}

Answer №2

Utilizing Vue 3, the following method can be employed:

  app.config.globalProperties.$keycloak = keycloak;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Polymer Integrated Binding for Advanced Search Options

Here is my code snippet to bind a tree in the Office->Team->"user" hierarchy. The main requirement is to enable user search functionality. To bind the tree, I have processed the users array to fit the required hierarchy. For searching, I filter out ...

The MD5 encryption varies from one another

When using SQL Server: 0x5C8C8AAFE7AE37EA4EBDF8BFA01F82B8 SELECT HASHBYTES('MD5', convert(varchar,getdate(),112)+'mytest@+') With JavaScript: 5c8c8aafe7ae37ea4ebdf8bfa01f82b8 // Function to get MD5 Hash bytes vm.getMd5Hashbytes = fun ...

Error: Loop Program Encountered Unexpected Token Syntax

Every time I attempt to run this code, a syntax error (unexpected token) appears. As someone who is still learning JavaScript, I am struggling to identify the root cause of this issue. var x = 1; var example = function(){ for(var y = 0; y < ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

Adjust the panel size accordingly for smaller screens

My application is utilizing the Spotify API to retrieve names and images. These are then displayed on my webpage within cards/panels in the following format: <div class="col-md-4" v-if="type == 'tracks'" v-for="(track, index) in tracks"> ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

using an x-api-key in the header of a service within Angular

I have been struggling with calling an x-api-key in the header of my Angular service, and I'm encountering an authorization error. It seems like there may be a syntax issue in my code. import { Injectable } from '@angular/core'; import { Htt ...

Replicate form element

I am having trouble duplicating form items Greetings to all. I have a form and I'm looking to add a button that allows users to duplicate fields each time they click on it. Here is my form: <v-layout v-for="(phone, index) in people.phones" :key=" ...

Is there a way to reduce the size or simplify the data in similar JSON objects using Node.js and NPM packages?

Is it possible to serialize objects of the type "ANY_TYPE" using standard Node tools.js or NPM modules? There may be multiple objects with this property. Original Json - https://pastebin.com/NL7A8amD Serialized Json - https://pastebin.com/AScG7g1R Thank ...

Turning JSON data into an array format, omitting the keys

Can someone help me with a query that will retrieve a specific column from the database and return it in this format: [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" } ] I would like to transform ...

Choose autocomplete feature from an external source within the context of AngularJS

I am currently working on an autocomplete textbox and I stumbled upon this script that I found through my search efforts. .controller('autoCompleteCTRL', function($scope, $rootScope){ $rootScope.searchItems = [ "ActionScript", ...

I encountered an issue with rendering static images when attempting to package my node-express app with pkg

Struggling to display an image from the public folder in my express app? I could use some guidance on configuring the path to properly render images or css files within the public folder when creating an executable file using pkg. Here's a snippet of ...

"Utilize JavaScript to extract data from JSON and dynamically generate a

I'm currently facing an issue with reading JSON data and populating it in my HTML table. The function to load the JSON data is not working as expected, although the data typing function is functioning properly. I have shared my complete HTML code alo ...

Implementing Vue class binding within a Rails image_tag

How can I output an image tag with a dynamically bound class using Rails for Vue integration? I am trying to bind the class in Vue like so: <img src="triangle.png" :class="{'asc': !sort_by_desc, 'desc': sort_by_desc}"/> When co ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

Comparing dynamic and static strings within objects using regex in JavaScript

Suppose there is an object with keys as strings containing dynamic values- let obj = { "/prodp/v1/engagemnt/{engID}/doc/{docID}": "roles_1", "/prodp/v1/engagemnt/{engID}/review/{reviewID}": "roles_2" } How can I find the value in the above object for the ...

The ng-change and onchange events are not functioning as expected for the input field with the type "file"

<button ng-click="controller.foo()">Click<button> is functioning properly. However, <input type="file" ng-model="logo" onchange="controller.foo()"> seems to be malfunctioning. Additionally, <input type="file" ng-model="logo" ng-ch ...

Deactivate all dropdown menus with the root event

I have come across a unique scenario in my user interface where I need to close all open b-dropdown components, including b-nav-item-dropdown. Unfortunately, I have not been able to find a straightforward solution similar to the one b-tooltip offers. thi ...

Tips for enabling or disabling elements within an array using React JS

I am looking to develop a feature where I can toggle individual boxes on and off by clicking on them. Currently, only one box at a time can be activated (displayed in green), but I want the ability to control each box independently without affecting the ot ...

I'm encountering an error in my terminal while running the code

ERROR *Server started on port 4000 Database ErrorMongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 (node:1616) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 at NativeConnection.Connec ...