You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Keycloak保护的Vue应用添加着陆页

解决Quasar+Keycloak实现未认证跳转首页而非直接登录的需求

需求说明

当前未认证用户访问所有页面都会直接跳转到Keycloak登录页,现在需要实现:

  • 访问http://192.168.0.105:9000/products时,已认证用户直接进入产品页,未认证用户跳转至/home首页
  • 首页包含登录按钮,点击后跳转至Keycloak登录页,登录成功后返回目标页面

1. 修改Keycloak Boot文件配置

原配置中onLoad: "login-required"会强制未认证用户直接跳转登录,需要改为check-sso仅检查认证状态,同时添加路由守卫逻辑控制页面跳转:

import { boot } from 'quasar/wrappers'
import Keycloak from "keycloak-js";

const keycloak = new Keycloak({
  url: "http://192.168.0.105:8080/auth",
  realm: "my-app-realm",
  clientId: "eo-fe-client",
});

export default boot(async ({ router }) => {
  await keycloak.init({
    onLoad: "check-sso", // 仅检查认证状态,不自动跳转登录
    checkLoginIframe: false,
    redirectUri: window.location.origin // 通用重定向URI,适配所有页面
  })
  .then((auth) => {
    // 配置全局路由守卫
    router.beforeEach((to, from, next) => {
      // 标记需要认证的路由
      const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
      
      if (requiresAuth && !keycloak.authenticated) {
        // 未认证访问需要权限的页面,跳转到首页,并记录原目标页
        next({ path: '/home', query: { redirect: to.fullPath } });
      } else if (!requiresAuth && keycloak.authenticated && to.path === '/home') {
        // 已认证用户访问首页,自动跳转到产品页(可根据需求调整)
        next({ path: '/products' });
      } else {
        next();
      }
    });

    // 保持Token自动刷新逻辑
    if (auth) {
      setInterval(() => {
        keycloak.updateToken(70).then((refreshed) => {
          refreshed && console.log("Access token refreshed!");
        }).catch(() => {
          console.error("Failed to refresh auth token!");
          keycloak.logout();
        });
      }, 60000);
    }
  })
  .catch(err => {
    console.error("Keycloak初始化失败:", err);
  });
});

export { keycloak }

2. 配置路由元信息

在路由配置文件(如src/router/index.js)中,给需要认证的路由添加meta.requiresAuth: true标记:

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: () => import('pages/Home.vue'),
    meta: { requiresAuth: false } // 无需认证即可访问
  },
  {
    path: '/products',
    name: 'Products',
    component: () => import('pages/Products.vue'),
    meta: { requiresAuth: true } // 必须认证才能访问
  },
  // 其他路由配置...
];

3. 首页添加登录按钮

在Home.vue中实现登录按钮,点击后调用Keycloak登录方法,并指定登录成功后的重定向地址:

<template>
  <div class="home-page">
    <h1>欢迎来到应用首页</h1>
    <q-btn 
      label="登录进入产品页" 
      color="primary"
      size="lg"
      @click="handleLogin"
    />
  </div>
</template>

<script>
import { keycloak } from 'boot/keycloak';

export default {
  methods: {
    handleLogin() {
      // 优先跳转到用户原本想要访问的页面,默认跳转到产品页
      const targetPath = this.$route.query.redirect || '/products';
      keycloak.login({
        redirectUri: `${window.location.origin}${targetPath}`
      });
    }
  }
}
</script>

4. Keycloak后台配置验证

确保Keycloak客户端的Valid Redirect URIs列表中包含以下地址:

  • http://192.168.0.105:9000/*(通配符适配所有页面)
    或更具体的:
  • http://192.168.0.105:9000/home
  • http://192.168.0.105:9000/products

内容的提问来源于stack exchange,提问作者Djole Pi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:24:52