2017-02-12 81 views
0

我具有由固定Keycloak角2應用,舉例here完成。角2,Keycloak:固定某些路線

我想知道,我怎樣才能確保某些路線。

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(); 
    }); 
    }); 
} 
.... 
+0

請改善您的問題。問題應該直接包含代碼的基本部分,而不僅僅是一個到外部資源的鏈接。你試過了什麼,你哪裏失敗了?實際和預期的行爲是什麼?錯誤消息,...? –

回答

0

這裏是我的解決方案,希望這會有所幫助的人:

  1. 刪除從main.ts keycloak初始化和自舉的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()); 
          } 
         } 
        }); 
    } 
    
3

您可以使用保護您的路線,我有下一個實現:

app.routes.ts:

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

家是受保護的路線,其他是免費的。

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是相似的。

我希望能有所幫助。