我有 Keycloak 保护的 Angular 2 应用程序,由示例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();
});
});
}
....
答案 0 :(得分:3)
你可以为你的路线使用Guard,我有下一个实现:
app.routes.ts:
export const rs: Routes = [
{ path: 'home', component: PersonAppComponent, canActivate: [AuthGuard] },
{ path: 'other', component: LoginComponent },
];
Home是受保护的路由,其他是免费访问。
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;
}
}
我的主要内容很相似。
我希望能提供帮助。
答案 1 :(得分:1)
这是我的解决方案,希望它对某人有所帮助:
像往常一样从main.ts keycloak初始化和boostrap AppModule中删除:
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
在 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());
}
}
});
}