Git Product home page Git Product logo

vue-keycloak-js's Introduction

vue-keycloak plugin

Known Vulnerabilities npm npm NPM

Introduction

This plugin uses the official Keycloak JS adapter https://github.com/keycloak/keycloak/tree/main/js/libs/keycloak-js

Please read the documentation: http://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter

Excerpt from Keycloak JS doc:

By default to authenticate you need to call the login function. However, there are two options available to make the adapter automatically authenticate. You can pass login-required or check-sso to the init function. login-required will authenticate the client if the user is logged-in to Keycloak or display the login page if not. check-sso will only authenticate the client if the user is already logged-in, if the user is not logged-in the browser will be redirected back to the application and remain unauthenticated.

To enable login-required set onLoad to login-required and pass to the init method:

keycloak.init({ onLoad: 'login-required' })

Installation

Install using npm

npm install @dsb-norge/vue-keycloak-js --save

Install using yarn

yarn add @dsb-norge/vue-keycloak-js

Usage

Vue 2

Vue.use(VueKeyCloak, [options])

Tell Vue to install the plugin, and optionally pass in a JavaScript object for additional configuration.

import VueKeyCloak from '@dsb-norge/vue-keycloak-js'

Vue.use(VueKeyCloak)

// You can also pass in options. Check options reference below.
Vue.use(VueKeyCloak, options)

Vue 3

createApp(App).use(VueKeycloak, [options])

Tell Vue to install the plugin, and optionally pass in a JavaScript object for additional configuration.

import VueKeyCloak from '@dsb-norge/vue-keycloak-js'

createApp(App).use(VueKeycloak)

// You can also pass in options. Check options reference below.
createApp(App).use(VueKeycloak, options)
import VueKeyCloak from '@dsb-norge/vue-keycloak-js'
import { VueKeycloakInstance } from "@dsb-norge/vue-keycloak-js/dist/types";

createApp(App).use(VueKeycloak)

// You can also pass in options. Check options reference below.
createApp(App).use(VueKeycloak, options)

// Allow usage of this.$keycloak in components
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties  {
    $keycloak: VueKeycloakInstance
  }
}

The plugin adds a $keycloak property to the global Vue instance. This shadows most of the keycloak instance's properties and functions. All other variables & functions can be found on $keycloak.keycloak attribute

Internally for Vue 2:

Internally for Vue 3

This object is reactive and will update with new tokens and other information

These properties/functions are exposed:

{
  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
  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
  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
  keycloak: Object             // The original keycloak instance 'as is' from keycloak-js adapter
}

Options

You can pass in an object as options to the plugin. The following keys are valid options. See below for description.

Key Type Default
config String | Object window.__BASEURL__ + '/config'
init Object {onLoad: 'login-required'}
logout Object
onReady Function(keycloak)
onInitError Function(error, keycloakError)
onInitSuccess Function(authenticated)
onAuthLogout Function(keycloak)
onAuthRefreshError Function(keycloak)
onAuthRefreshSuccess Function(keycloak)

config

The config object, either returned from an endpoint (string) or set directly (object), must be compatible with the Keycloak JS adapter constructor arguments.

See description below.

String

If this option is a string, the plugin will treat it as an URL and make an HTTP GET request to it.

If not present, the plugin will look for a global variable window.__BASEURL__ and prepend it to '/config' and use this a default place to make a GET request.

If no window.__BASEURL__ exists, /config is used.

The return value from the request is used as constructor parameters for the Keycloak adapter. As such, it should be an object with valid keys/values.

See Keycloak's Javascript adapter reference

E.g.

{
  realm: String,
  url: String,
  clientId: String
}

These values will be used as constructor parameters to the official Keycloak adapter.

Object

If this option is an object, it will be passed on as constructor parameters for the Keycloak adapter. No HTTP GET request is done in this case.

init

This option is the parameter object for the Keycloak.init method.

logout

This option is the parameter object for the Keycloak.logout method.

onReady

This option is a callback function that is executed once Keycloak has initialised and is ready. You can be sure that the Vue instance has a property called $keycloak in this function. See above for possible values.

The callback function has one parameter, which is the keycloak object returned from the Keycloak adapter on instantiation.

One use case for this callback could be to instantiate and mount the Vue application. Then we are sure that the Keycloak authentication and the $keycloak property are properly finished and hydrated with data:

Vue.use(VueKeyCloak, {
  onReady: (keycloak) => {
    console.log(`I wonder what Keycloak returns: ${keycloak}`)
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      template: '<App/>',
      render: h => h(App)
    })
  }
})

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

function tokenInterceptor () {
  axios.interceptors.request.use(config => {
    if (Vue.prototype.$keycloak.authenticated) {
      config.headers.Authorization = `Bearer ${Vue.prototype.$keycloak.token}`
    }
    return config
  }, error => {
    return Promise.reject(error)
  })
}

Vue.use(VueKeyCloak, {
  onReady: (keycloak) => {
    tokenInterceptor()
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      template: '<App/>',
      render: h => h(App)
    })
  }
})

onInitError

This option is a callback function that is executed if Keycloak initialisation has failed.

The callback function has one parameter, which is the error object returned by Keycloak. Note that this may be undefined even though an error has occurred, as Keycloak does not return an error object in every error case.

onInitSuccess

This option is a callback function that is executed if Keycloak initialisation has succeeded.

The callback function has one parameter, which is the authenticated value returned by Keycloak's init method.

onAuthLogout

This option is a callback function that is executed if the user is logged out (will only be called if the session status iframe is enabled, or in Cordova mode).

The callback function has one parameter, which is the keycloak object returned from the Keycloak adapter on instantiation.

onAuthRefreshError

This option is a callback function that is executed if there was an error while trying to refresh the token.

The callback function has one parameter, which is the keycloak object returned from the Keycloak adapter on instantiation.

onAuthRefreshSuccess

This option is a callback function that is executed when the token is refreshed.

The callback function has one parameter, which is the keycloak object returned from the Keycloak adapter on instantiation.

Examples

Supply a configuration object for the Keycloak constructor

Vue.use(VueKeyCloak, {
  config: {
    realm: 'MyRealm',
    url: 'https://my.keycloak.server/auth',
    clientId: 'MyClientId'
  },
  onReady: kc => {
    new Vue({
      render: h => h(App)
    }).$mount('#app')
  }
})

Supply init option (disable monitoring login state)

Vue.use(VueKeyCloak, {
  init: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  onReady: kc => {
    new Vue({
      render: h => h(App)
    }).$mount('#app')
  }
})

Supply init option (use check-sso)

Remember; login-required is the default value for the onLoad property in the init object. So without passing an init object as argument, the default is { init: 'login-required' }

To avoid waiting for configuration endpoint before loading vue app:
Vue.use(VueKeyCloak, {
  init: {
    onLoad: 'check-sso'
  }
})

new Vue({
  render: h => h(App)
}).$mount('#app')
Wait until keycloak adapter is ready before loading vue app:
Vue.use(VueKeyCloak, {
  init: {
    onLoad: 'check-sso'
  },
  onReady: kc => {
    new Vue({
      render: h => h(App)
    }).$mount('#app')
  }
})

Specify a redirectUri

Vue.use(VueKeyCloak, {
  logout: {
    redirectUri: 'https://mydomain.lives.here.com'
  },
  onReady: kc => {
    new Vue({
      render: h => h(App)
    }).$mount('#app')
  }
})

Example applications

View a complete example app, with router guards:

hello-keycloak

Simple 'in component' secret displaying reactiveness:

simple_vue2

Typescript example with vue 3

typescript_vue3

How to release

$ git checkout main
$ npm version [major | minor | patch ]
$ git push
$ git push --tags

Go to GitHub and create a new release based on the latest tag. GitHub Actions will then build and publish the release to npmjs.com.

Frequently asked questions

We try to answer the most frequently asked questions here.

Localhost !== 127.0.0.1

Note that if you run keycloak on your own machine it is important to be consistent with the settings for its address. Cookies created from 127.0.0.1 will not be sent to "localhost" and vice versa.

vue-keycloak-js's People

Contributors

anderius avatar baltom avatar chrisnruud avatar christopherruud avatar dependabot[bot] avatar eidottermihi avatar idc77 avatar jakubserwin avatar manuelkasper avatar mend-bolt-for-github[bot] avatar micha-b avatar mllull avatar nd0ut avatar nlien avatar renovate-bot avatar renovate[bot] avatar rolv79 avatar simenrokaas avatar wirk avatar yarkovaleksei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-keycloak-js's Issues

How to login

So currently I'm able to login by making the init options - login-required. Doing so will forcefully check if I'm currently logged-in upon load, but if not I will be redirected to the keycloak login page.

But what if my current setup is it allows guest, therefore login is not required during app load. How can I manually redirect the page to the Keycloak login page? I was thinking maybe there is a function I can call which I will attach to a button?

I get unauthorized after ~10 mins

"@dsb-norge/vue-keycloak-js": "^1.1.3",

Vue.use(VueKeyCloakJs, {
init: {
onLoad: 'login-required'
},
config: {
url: process.env.VUE_APP_SSO_URL,
realm: process.env.VUE_APP_SSO_REALM,
clientId: process.env.VUE_APP_SSO_CLIENTID
},
...
})

In the console I have:
Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘https://url’) does not match the recipient window’s origin (‘null’).

What am I missing?

Not working with Keycloak 5.0.0?

Hi there.

I've upgraded my keycloak server from version 4.5.0 to 5.0.0 and now users are being logged out after a few seconds after logging in. No output in console, no errors.

Could this be a compatibility problem with KC 5.0.0?

Thanks.

Re-use config parameter names from the Keycloak adapter

It is confusing to use authRealm, and not realm. We should probably find a way, without breaking backwards compatibility, to use the same names as Keycloak uses. And possibly simply pass the entire config objects info the adapter.

Adding idpHint to the configuration?

Is it somehow possible to add idpHint to the configuration of Keycloak?

I tried to use config and init but it seems that this option is only available in the login method of keycloak.

Vue.use(VueKeyCloak, {
    init: {
        onLoad: 'login-check',
        idpHint: 'azure,' // NOT WORKING
        checkLoginIframe: false
    },
    config: {
        realm: 'mypublicrealm',
        url: 'https://mypublicrealm.com/auth',
        clientId: 'fa7e101c'
    },
    onReady: () => {
        new Vue({
            router,
            store,
            components: LocalComponents,
            el: '#app',
            render: h => h(GlobalComponents.App)
        })
  }
});

How to override login redirect_uri

I am using router.beforeEach to determine which routes require auth. Works fine.

However, after logging out, it's desirable to allow a person to navigate to a route that requires authentication. When they click a route requiring auth, I can get it to correctly call the login function, but I can't seem to control the redirect_uri. It seems to always just use the route you are on (in this case /logout), instead of the route you are trying to go to. Passing in a string to loginFn doesn't seem to do anything. Is there a way to override the redirect_uri when calling loginFn?

Infinite refresh every 5 sec

I have a problem.
In different browsers I can see page refresh every 5 sec.
In some time keycloak.authenticated states is false.
App is redirecting to login page where understanding that token is valid.
I think that depends of browsers setting or plugins because I don't have it before update Safari to new version.
However, my colleague has that problem from starting project

`import Vue from 'vue';
import App from './App.vue';
import store from './store';
import router from './router';
import VueKeyCloak from '@dsb-norge/vue-keycloak-js';
import { initAxios, vuetify } from './plugins';
import i18n from './i18n';

Vue.config.productionTip = false;

let keycloak = null;

Vue.use(VueKeyCloak, {
config: {
url: process.env.VUE_APP_KEYCLOAK_URL,
realm: process.env.VUE_APP_KEYCLOAK_REALM,
clientId: process.env.VUE_APP_KEYCLOAK_CLIENT_ID,
},
init: {
onLoad: 'login-required',
},
onReady: kc => {
keycloak = window.keycloak = kc;
initKeycloak()
.then(() => initAxios(kc.token))
.then(initApp)
.catch(authenticate);
},
});

function initApp() {
new Vue({
store,
router,
vuetify,
i18n,
render: h => h(App),
}).$mount('#app');
}

function initKeycloak() {
return new Promise((resolve, reject) => {
if (!keycloak.authenticated) reject(Error('401'));
else {
protectRoutes();
resolve();
}
});
}

function protectRoutes() {
router.beforeEach((to, from, next) => {
keycloak.authenticated ? next() : authenticate();
});
}

function authenticate() {
if (keycloak.authenticated) return;
window.location.replace(keycloak.createLoginUrl());
}
`

token not refresh

i'm trying to understand why my token is not refreshed.

i have configured SSO Session max to : 2 minute

in my console :

After 1 min, every ten second :
dsb-vue-keycloak.umd.js:464 [KEYCLOAK] Refreshing token: token expired
dsb-vue-keycloak.umd.js:491 [KEYCLOAK] Token refreshed
dsb-vue-keycloak.umd.js:840 [KEYCLOAK] Estimated time difference between browser and server is 0 seconds

At 2 min :
dsb-vue-keycloak.umd.js:516 POST http:*******
dsb-vue-keycloak.umd.js:501 [KEYCLOAK] Failed to refresh token
dsb-vue-keycloak.umd.js:1650 Error while trying to refresh the token

Javascript plugin token not compatible with Java plugin token

this may be an issue for the keycloak team but they are usually pretty busy. if i login first using the javascript plugin and then navigate to a java endpoint secured by the java keycloak plugin (tomcat) then it gives me an infinite redirect error. however if i login using the java version and navigate to the javascript version it is fine. i have checked the cookies and they seem near identical. it is strange.

Remove dist folder from git

To prevent people (myself included) from making changes in the wrong place, I suggest removing the dist folder from git.

Error handling when the Keycloak service is unavailable.

When using this plugin a Vue instance is mounted after the plugin has been initialised (and the onReady is called). When the Keycloak server is unavailable the onReady is never called and thus the Vue instance not mounted. The result is a black page when starting the frontend application. Is there a way to catch this error situation (maybe with an onError)?

The official plugin (keycloak-js-bower) does not seem to have a function for this but maybe there is a way to catch this error situation. The only feedback I have now is the following message which is logged in the browsers console:

Failed to load resource: the server responded with a status of 503 (Service Unavailable).

Not sure of the proper use

Hello,

I am using the component in quasar and despite my keycloak settings, my app keeps asking for logging too often. I would like to be sure that I am using the component the right way.

In particular, I don't use the refresh token because it seems the component is silently working to refresh the access. Is it right? If not, what is the good practice for the refresh token?

Sorry, this is probably a very noob and silly question,
thanks

How to skip some routes?

Hi, everyone

How to skip some routes, I mean I just need keycloak auth in specific routes?

Thanks.

accessing $keycloak within Router

Hello,

I am struggling with getting access to $keycloak in the Router. Any suggestions or examples on how to accomplish this?

Thanks, I appreciate any advice!

Server side rendering support

The NuxtJS framework has server-side rendering out of the box (in universal mode) and there are some errors since the lib uses window global variable. The code that uses window must be wrapped with the condition like if (process.browser) { ... } but there might be something else. Thanks!

Why abandoning yarn?

Hello,

we use Yarn at my office to manage our JavaScript project, but your package is explicitly not compatible with it anymore (although you feature it in the installation section of the README).

Can we know the reason for this choice, and if there is any way (other than forking the project) to have it work under Yarn?

Infinite redirection loop with vue-router default mode "hash"

Hi,
it's more a question that a real issue, because I'm not sure if I configured something wrong or if I missed something.
The plugin works great with vue and vue-router when it's configured to use the mode history. If the default mode "hash" is set, after completing login, the page is redirected indefinitely.
Do you have any clue?

Thanks!

CORS issue

I am using Keycloak 4.5.0 and I seem to bump into a CORS issue.

Access to XMLHttpRequest at 'https://securetest.mydomain.com/auth/realms/homeconvey-production/protocol/openid-connect/token' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have added the Web Origin 'http://localhost:8081' to the Client that I am using.

Support for IE11

In IE11 I'm getting "Object doesn't support property or method 'includes'"
If you change includes on line 1869 to indexOf in dsb-vue-keycloak.umd.js it will also support IE11

Access to profile email

It would helpful if the keycloak instance contained the user's email attribute from tokenParsed.

It might be good to make a more open way of accessing the tokenParsed

TypeScript support

Hi,

Are you planning to add TypeScript support in the future?

Thanks!

Expose keycloak instance

It would be interesting to expose the internal keycloak instance this library is wrapping, so that we could access other features the tool has. Such as the loadUserProfile method (among others).

How can I use the login token access spring boot rest api?

Recently I use jhipster to create a spring boot project which select keycloak to protect my rest api, and the application.properties like this:

  security:
    oauth2:
      client:
        provider:
          oidc:
            issuer-uri: http://localhost:9080/auth/realms/jhipster
        registration:
          oidc:
            client-id: web_app
            client-secret: web_app

also, I create a vue project which select keycloak js to protect pages, the config like this:

import VueKeyCloak from '@dsb-norge/vue-keycloak-js'

Vue.use(VueKeyCloak, {
  config: {
    realm: 'jhipster',
    url: 'http://127.0.0.1:9080/auth',
    clientId: 'web_app'
  },
  onReady: (keycloak) => {
    console.log(keycloak.token)
    new Vue({
      el: '#app',
      router,
      store,
      render: h => h(App)
    })
  }
})

And we can see the vue project and spring project use the same keycloak client id, the Access Type is public in keycloak.
In vue project, I need to use username and password to log in,
log in page
after log in I can get a token through keycloak.token, and I also set

config.headers.Authorization = `Bearer ${Vue.prototype.$keycloak.token}`

when I call spring boot rest api. But not working, always return 401.
After several days hard working, I can not find the reason. Someone can help me?

Thank you very much.

Redirect URI configuration

Hi,

the Keycloak JS Adapter reference describes the method login(options) where the object options includes setting a redirect URI.

As far as I can see, vue-keycloak-js does not expose the options object of the login method. Therefore, the Keycloak Javascript Adapter always uses the current URI as redirect URI.

Because a user might refresh the page on any URI, the redirect URI of the client must be configured using a wildcard (i.e. example.com/*).
Is there any way around this? I want to configure my redirect URI as strict as possible.

Infinite refresh attempts with expired refresh token

If the plugin is without internet access for a while (laptop in hibernation etc), the refresh token expires.
After this, it still tries to refresh, which will never success.

A possible fix can be to expose the keycloak object, and let the users handle all callbacks, including onAuthRefreshError.

onReady never fires, without error

What am i missing ? this console log never fires

My main.js code:

Vue.use(VueKeycloak, {
  init: {
    onLoad: 'login-required',
    checkLoginIframe: false,
  },
  config: {
    realm: 'master',
    url: 'https://mykeycloak/auth',
    clientId: 'client11',
  },
  onReady: keycloak => {
    console.log(`I wonder what Keycloak returns: ${keycloak}`);
    // eslint-disable-next-line no-new
    new Vue({
      el: '#app',
      store,
      router,
      render: h => h(App),
    });
  },
});

How to Logout?

hello,

how can I execute the logout from the current user?

also, how can I force reauthentication?

thank

The Fuction hasRealmRole has some problem

Hello, I found some problems with the function 'hasRealmRole'.
I confirm if the account is admin by the function.
this.$keycloak.hasRealmRole('C_ADMIN')
But I found it get true then get false sometimes.
I don't know what happened.
So finally I use this.$keycloak.realmAccess.roles.includes('C_ADMIN')

Typescript support

Hi,

Can you please add ts support ?

I use Vue with TS and I get this error:
Could not find a declaration file for module '@dsb-norge/vue-keycloak-js'

Thanks

Trigger updateToken

Thanks for this helpful plugin.

I understand that there is an implicit token refresh, but I would like to trigger updateToken() before making an API call (or) as a part of error handling of an 403 response, like how it's mentioned in the JS adapter docs. How do I do this?

I did try $keycloak.updateToken but this function is not exposed with the $keycloak instance. Is there any other way? Thanks in advance!

keycloak.updateToken(60).then(function() {
    makeAPICall();
}).catch(function() {
    alert('Failed to refresh token');
});

hello-keycloak example does not run on Mircrosoft Edge

Hello,

If you just run the hello-keycloak example, you will realize that is does not work on Microsoft Edge, It makes the redirect to the keycloak server to authentication but when it returns, nothing happens.

I think that there is something with the Promise support...

How to setup babel to proper work with vue-keycloak?

thanks for all the help

Session lost on window refresh

Hi guys,

I found that this lib is working fine if you log in throught keycloak, but if you refresh window (tipically if you are developing the app), it loses the session and have to re-enter keycloak for login.

You can try it in example-app. if you enter /secret , you could see token info. But if you press F5, you keep on /secret page but there is no token. This is because keycloak lib doesn't authenticate the user.

I have googled but can't find how to read cookie session and pass it to keycloak lib to authenticate.

Specify that 127.0.0.1 not same as localhost

I know this is not a big issue but just in case anyone spends 2 hours trying to debug the plugin 127.0.0.1 cookies are not the same as http://localhost cookies.

I would login with localhost and it would load initially but when I refreshed it would appear as not authenticated which is what caused the most confusion.

Add keycloak token to Vuex store

Hi,

I'm wondering how I can add the keycloak token to the Vuex store and have it automatically update when the token is updated. Below is the content of my main.js file. Any guidance is appreciated. Thanks.

import Vue from "vue";
import "./plugins/axios";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from "./plugins/vuetify";
import VueKeycloakJs from "@dsb-norge/vue-keycloak-js";

Vue.config.productionTip = false;

Vue.use(VueKeycloakJs, {
  init: {
    // Use 'login-required' to always require authentication
    // If using 'login-required', there is no need for the router guards in router.js
    onLoad: "check-sso"
  },
  config: {
    url: process.env.VUE_APP_KEYCLOAK_URL,
    clientId: process.env.VUE_APP_KEYCLOAK_FRONTEND_CLIENT_ID,
    realm: process.env.VUE_APP_KEYCLOAK_REALM
  }
});

new Vue({
  router,
  store,
  vuetify,
  render: h => h(App)
}).$mount("#app");

How to detect when the token has expired

If i leave my PC for a long time or overnight then sometimes the page may still be loaded but the token is expired. it would be nice to be able to check for this and redirect to the login page. i am using check-sso

$keycloak property always "empty"

I am facing a problem using this lib:

I can render the login page, do the login action, but when I am redirected to my application, the $keycloack properties are null (token, tokenParsed, ...) and authenticated is false, even I can use the application.

Also, looks like the onReady callback is not fired, and onInitError is always fired with undefined error object.

My admin console in keycloak server shows that my user is logged in, even the $keycloak.authenticated is false

I am using this lib with nuxtjs, but in SPA mode.

Protected urls

Hello,

Would it be possible to require authentication only on certain routes?

Thanks.

Roles

How can I call the underlying keycloak adapter's hasRealmRole( ) function? I am missing how to check roles with this plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.