dsb-norge / vue-keycloak-js Goto Github PK
View Code? Open in Web Editor NEWA Keycloak plugin for Vue 2
Home Page: https://www.dsb.no
License: ISC License
A Keycloak plugin for Vue 2
Home Page: https://www.dsb.no
License: ISC License
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 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());
}
`
To prevent people (myself included) from making changes in the wrong place, I suggest removing the dist folder from git.
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!
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!
would be great to have a small vue example project, which shows usage ans integration of the plugin
Hi guys,
Thanks a lot for the plugin, it helps me a lot !!
I wrote and shared a "full demo" of integration, you can find it here https://github.com/mimiz/vue-auth-test Feel free to make me any comments ...
Regards and thank you !
Rémi
Hi, everyone
How to skip some routes, I mean I just need keycloak auth in specific routes?
Thanks.
hello,
how can I execute the logout from the current user?
also, how can I force reauthentication?
thank
Because Vue 3.0 is here......
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.
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.
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
Does this library support grant_type
as Password Credentials? I want to just pass username and password and get access token.
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
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
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,
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.
How do I provide a client secret in the config object?
error: "unauthorized_client"
error_description: "Client secret not provided in request"
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).
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!
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.
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 can I use pkceMethod as on the keycloak.js?
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')
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.
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');
});
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.
Hi,
Are you planning to add TypeScript support in the future?
Thanks!
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).
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)
})
}
});
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?
Hello,
Would it be possible to require authentication only on certain routes?
Thanks.
Document more examples of how to pass on configuration object etc.
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.
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
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");
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.
How can I call the underlying keycloak adapter's hasRealmRole( ) function? I am missing how to check roles with this plugin.
I have tried to register new user from Jhipster (Oauth2, keycloak) but getting authorization error.( based on bearer token ). If any reference, please let us know.
After receiving some questions around the use of client secret, I have create the following issue requesting a clarification:
https://issues.jboss.org/browse/KEYCLOAK-10276
Hopefully, we get some explanation we can include or point to from our doc.
It would be nice if you can update to the latest keycloak version
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.
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),
});
},
});
"@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?
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
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
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
.
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.