Keycloak 检查-sso 创建

Keycloak check-sso create

我正在使用 Angular 8.0.3、keycloak 8.0.0 和 keycloak-service 7.0.1

我正在尝试制作一些 public 页,所以我正在使用 'check-sso'。 如果我理解正确的话,如果用户没有登录,浏览器将被重定向回应用程序并保持未验证状态。

我的应用有这个路由:

const routes: Routes = [
  {
    path: '',
    loadChildren: () => import('src/app/pages/pages.module').then(m => m.PagesModule),
    canLoad: [IsAuthenticateGuard]
  },
  {
    path: 'login',
    component: LoginComponent,
    canLoad: [IsNotAuthenticateGuard]
  },
  {
    path: '**',
    redirectTo: ''
  }
]

守卫:

export class IsAuthenticateGuard implements CanLoad {

  constructor(private keycloakService: KeycloakService, private router: Router) {}

  canLoad(
    route: Route,
    segments: UrlSegment[]
  ): Observable<boolean>|Promise<boolean>|boolean {
    return this.keycloakService.isLoggedIn().then(isLogged => {
      if (!isLogged) {
        this.router.navigateByUrl('/login');
      }
      return isLogged;
    });
  }
}
export class IsNotAuthenticateGuard implements CanActivate {

  constructor(private keycloakService: KeycloakService,
              private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.keycloakService.isLoggedIn().then(isLogged => {
      if (isLogged) {
        this.router.navigateByUrl('/home');
      }
      return !isLogged;
    });
  }

}

我的 keycloak 有这个初始配置:

keycloakService.init({
        config: keycloakConfig,
        initOptions: {
          onLoad: 'check-sso',
          checkLoginIframe: false
        },
        bearerExcludedUrls: ['/login'] // (I tried also '.*')
      })

但我被重定向到:
http://localhost:4200/#error=login_required&state=0b36094c-92ac-4703-a800-77f27e4d206d
没有附加内容...

我读了这篇文章,但没有找到解决方案:

https://github.com/mauriciovigolo/keycloak-angular https://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter

您正在使用 onLoad: 'check-sso',它仅在用户登录后才对客户端进行身份验证。

您应该改用 onLoad: 'login-required'