要将Angular独立版与Keycloak集成,可以按照以下步骤进行操作:
keycloak-angular
库。npm install keycloak-angular
keycloak.json
的文件,并将Keycloak服务器的配置信息添加到该文件中。配置信息包括realm
、url
、clientId
等。{
"realm": "your-realm",
"url": "http://localhost:8080/auth",
"clientId": "your-client-id"
}
app.module.ts
文件,并按照以下方式导入KeycloakAngularModule
。import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';
@NgModule({
imports: [
KeycloakAngularModule,
// other imports
],
providers: [
KeycloakService,
// other providers
],
// other configurations
})
export class AppModule { }
app.component.ts
文件中,导入KeycloakService
并进行配置。import { Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
@Component({
selector: 'app-root',
template: ' '
})
export class AppComponent {
constructor(private keycloakService: KeycloakService) { }
async ngOnInit() {
try {
await this.keycloakService.init({
config: 'assets/keycloak.json',
initOptions: {
onLoad: 'check-sso',
checkLoginIframe: false
},
enableBearerInterceptor: true,
bearerExcludedUrls: ['/assets']
});
} catch (error) {
console.error('Keycloak init failed', error);
}
}
}
AuthGuardService
的服务,并导入KeycloakAuthGuard
。import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService extends KeycloakAuthGuard {
constructor(protected readonly keycloak: KeycloakService) {
super(keycloak);
}
async isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url
});
}
return this.authenticated;
}
}
AuthGuardService
来保护需要认证的路由。import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardService } from './auth-guard.service';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuardService] },
// other routes
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
KeycloakService
并使用其方法。import { Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';
@Component({
selector: 'app-protected',
template: 'Protected Component
'
})
export class ProtectedComponent {
constructor(private keycloakService: KeycloakService) { }
logout() {
this.keycloakService.logout();
}
}
这样,你的Angular应用就与Keycloak集成完成了。注意,在使用示例代码时,你需要根据你自己的Keycloak配置进行相应的修改。