前端接入keycloak的几种方式

方式一:keycloak-js

这种方式就像使用QQ登录一样,登录会跳转到 keycloak 给的登录界面。

安装:

npm i keycloak-js

使用:

import Keycloak from 'keycloak-js'
 
const keycloak: any = Keycloak({
  url: 'https://xxx.com/', // 远程地址
  realm: 'xxx',
  clientId: 'xxx'
})
keycloak.init({onLoad: 'login-required'}).then((auth: boolean) => {
  if (!auth) {
    window.location.reload();
  } else {
    new Vue({
      el: '#app',
      render: h => h(App, { props: { keycloak } })
    })
  }
})

详细请查看:Vue.js - Keycloak

vue3

import Keycloak from "keycloak-js";
 
const keycloak: any = Keycloak({
  url: "https://www.xxx.com/",
  realm: "xxx",
  clientId: "xxx",
});
 
keycloak.init({ onLoad: "login-required" }).then((auth: boolean) => {
  if (!auth) {
    window.location.reload();
  } else {
    const app = createApp(App);
    app.use(ElementPlus, { locale });
    app.use(createPinia());
    app.use(router);
 
    app.config.globalProperties.$keycloak = keycloak;
 
    app.mount("#app");
  }
})

退出登录

keycloak.logout()

方式二:vue-keycloak-js

这个是针对 vue 项目封装的 keycloak-js。
安装地址:@dsb-norge/vue-keycloak-js - npm

安装:

npm i @dsb-norge/vue-keycloak-js 

使用:

import VueKeycloakJs from '@dsb-norge/vue-keycloak-js'
 
Vue.use(VueKeycloakJs, {
  init: {
    onLoad: 'login-required'
  },
  config: {
    url: 'https://xxx.com/',
    realm: 'xxx',
    clientId: 'xxx'
  },
  onReady: (keycloak) => {
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount("#app")
 
    // 获取用户的信息
    // keycloak.loadUserProfile().success((data) => {
    //   console.log(data)
    // })
  }
})

详细请查看:Vue集成Keycloak_keycloak vue_s先生的d小姐的博客-优快云博客

方式三:RESTful API

这种方式可以使用自定义的登录界面。

axios.post(`/keycloak/realms/xxx/protocol/openid-connect/token`, {
  client_id: 'xxx',
  username: 'xxx',
  password: 'xxx',
  grant_type: 'password',
}).then(res => {
  console.log(res) // 会返回包含 access_token、refresh_token 等信息,access_token 可在线解析成明文数据:JSON Web Tokens - jwt.io
})

或者使用 jwt-decode 进行 access_token 解析。

接口代理:

server: {
  proxy: {
    '/keycloak/': {
      target: 'https://xxx.com/',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/keycloak/, ''),
    }
  }
},

其他接口请求需要加 token 验证(keycloak 使用的是 JWT):

axios({
  url: '/keycloak/user/list',
  headers: {
    'Authorization': `Bearer ${access_token}`
  }
}).then(res => {
  console.log(res)
})

刷新 token(默认:access_token有效期5分钟,refresh_token有效期30分钟)

axios.post(`/keycloak/realms/PVG/protocol/openid-connect/token`, {
  client_id: 'xxx',
  refresh_token: 'xxx',
  grant_type: 'refresh_token',
}, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

如果需要共享登录,可以使用同一级域名cookie试试,主要是要共享token。

原文链接: https://blog.youkuaiyun.com/weixin_44565273/article/details/130301871

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值