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

Angular中清除存储及隐身模式下Keycloak SSO不跳转登录页问题

问题原因分析与解决方案

核心原因1:未配置路由守卫拦截未认证请求

你当前的配置仅完成了Keycloak的初始化,但没有通过KeycloakAuthGuard保护路由。这意味着即使Keycloak检测到用户未认证,Angular路由也不会被拦截,会直接渲染首页组件,完全跳过身份校验环节。

核心原因2:check-sso模式的行为特性

onLoad: 'check-sso'的作用是静默检查已有SSO会话,而非强制用户登录:

  • 如果存在有效会话,自动完成认证;
  • 如果没有会话,不会主动跳转登录页,仅保持应用处于未认证状态。

结合未配置路由守卫的情况,就会出现“直接渲染首页、无身份校验”的现象。

补充排查点:Keycloak客户端配置

检查Keycloak控制台中你的SSO客户端是否存在以下配置问题:

  • 是否开启了直接访问授权(Direct Access Grants Enabled);
  • 是否在有效重定向URI中添加了两个应用的完整域名/端口;
  • 是否设置了无需认证的路径(Authorization > Permissions > Resources)。

修复步骤

1. 添加路由守卫

创建路由守卫文件(比如auth.guard.ts):

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard extends KeycloakAuthGuard {
  constructor(
    protected override readonly router: Router,
    protected readonly keycloakAngular: KeycloakService
  ) {
    super(router, keycloakAngular);
  }

  async isAccessAllowed(): Promise<boolean> {
    // 检查用户是否已认证
    if (!this.authenticated) {
      // 未认证时强制跳转登录页
      await this.keycloakAngular.login({
        redirectUri: window.location.origin + '/home' // 替换为你的首页路由
      });
      return false;
    }

    // 可按需添加角色校验逻辑
    // const hasRequiredRole = this.roles.includes('admin');
    // if (!hasRequiredRole) {
    //   this.router.navigate(['/unauthorized']);
    //   return false;
    // }

    return true;
  }
}

2. 在路由配置中使用守卫

修改app-routing.module.ts,为需要保护的路由添加canActivate: [AuthGuard]:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    canActivate: [AuthGuard] // 保护首页路由
  },
  // 其他需要保护的路由也添加该守卫
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

3. 调整Keycloak初始化配置(可选)

如果你希望应用启动时强制用户登录,可将onLoad改为login-required:

keycloak.init({
  config: {
    url: 'http://localhost:8080/',
    realm: 'myrealm',
    clientId: 'SSO',
  },
  initOptions: {
    onLoad: 'login-required', // 替换为login-required
    silentCheckSsoRedirectUri:
      window.location.origin + '/assets/silent-check-sso.html',
  },
});

注意:login-required会在应用启动时直接跳转登录页,适合必须认证才能访问的应用;而check-sso适合允许未认证用户访问部分内容的场景。

4. 验证silent-check-sso.html文件

确保assets/silent-check-sso.html文件存在且内容正确:

<!DOCTYPE html>
<html>
<body>
  <script>
    parent.postMessage(location.href, location.origin);
  </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Bennison J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:08:21