Angular 2、Keycloak:保护某些路由

Angular 2, Keycloak: securing certain routes

我有 Angular 2 应用程序由 Keycloak 保护,通过示例 here 完成。

我想知道,我怎样才能只保护某些路由。

main.ts:

 KeycloakService.init()
 .then(() => {
   const platform = platformBrowserDynamic();
   platform.bootstrapModule(AppModule);
 })
 .catch(() => window.location.reload());

keycloak.service.ts:

@Injectable()
export class KeycloakService {

  static auth: any = {};

  static loginUser: KeycloakUser;

  static init(): Promise<any> {

  let keycloakAuth: Keycloak.KeycloakInstance = Keycloak('keycloak/keycloak.json');

  KeycloakService.auth.loggedIn = false;

  return new Promise((resolve, reject) => {
    keycloakAuth.init({ onLoad: 'login-required' })
    .success(() => {
      KeycloakService.auth.loggedIn = true;
      KeycloakService.auth.authz = keycloakAuth;

      KeycloakService.auth.logoutUrl = keycloakAuth.authServerUrl + "/realms/demo/protocol/openid-connect/logout?redirect_uri=/angular2-product/index.html";
      resolve();
    })
    .error(() => {
      reject();
    });
   });
 }
 ....

这是我的解决方案,希望对某人有所帮助:

  1. 照常从 main.ts keycloak 初始化和 boostrap AppModule 中删除:

    if (environment.production) {
        enableProdMode();
    }
    
    platformBrowserDynamic().bootstrapModule(AppModule);
    
  2. app.component.ts中添加:

    import { Router, NavigationStart } from '@angular/router';
    ...
    
    constructor(private router: Router) {
      router.events.forEach(element => {
          if (element instanceof NavigationStart && 
             (element.url === '/secure-route-1' || 
              element.url === '/secure-route-2')) {
    
            if (!KeycloakService.auth.loggedIn) {
                 KeycloakService.init()
                    .then(() => {})
                    .catch(() => window.location.reload());
               }
          }
      });
    } 
    

你可以为你的路线使用守卫,我有下一个实现:

app.routes.ts:

export const rs: Routes = [
  { path: 'home',  component: PersonAppComponent, canActivate: [AuthGuard] },
  { path: 'other',  component: LoginComponent },
];

home是受保护的路线,other是免费的。

auth-guard.ts:

@Injectable()
export class AuthGuard implements CanActivate,OnInit {

  constructor(private ck: KeycloakService) {
    console.log("INIT AuthGuard: " + KeycloakService.auth.loggedIn )
  }

  ngOnInit() {

  }

  canActivate() {
    console.log("check guard: " + KeycloakService.auth.loggedIn)
    return KeycloakService.auth.loggedIn;
  }

}

我的main.ts也差不多。

希望对您有所帮助。