This is a project template that integrates Keycloak authentication server to an Angular5 project. It provides an authentication guard service that can restrict a component from being accessible if a user is not logged in.
*If you would like to support these tutorials, you can contribute to my Patreon account
This is a project template that integrates Keycloak authentication server to an Angular5 project.
It provides an authentication guard service that can restrict a component from being accessible if a user is not logged in.
Blog: https://czetsuya-tech.blogspot.com/2019/08/how-to-secure-angular-app-with-keycloak.html
This project was tested on:
To update the angular CLI version:
npm uninstall --save-dev angular-cli
npm cache verify
npm install --save-dev @angular/cli@latest
To update the dependencies
npm i -g npm-check-updates
ncu -u
npm install
To run Keycloak using docker, open your command prompt and execute:
docker run --name=keycloak_11 -p 8081:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin jboss/keycloak:11.0.3
The following are configurations on how to secure routes.
1.) To secure a component by authenticated user:
{ path: 'secured', canActivate: [AuthGuard], component: SecuredComponent },
2.) To secure a module by group membership:
{
path: 'groupRestricted',
canLoad: [AuthGuard],
loadChildren: 'app/group-restricted/group-restricted.module#GroupRestrictedModule',
data: {
Permission: {
Only: ['User'],
RedirectTo: '403'
} as PermissionGuard
}
}
3.) To secure a module by role membership:
{
path: 'secured-role',
canLoad: [AuthGuard],
loadChildren: 'app/group-restricted/group-restricted.module#GroupRestrictedModule',
data: {
Permission: {
Only: ['User'],
RedirectTo: '403'
} as PermissionGuard
}
}
1.) If you migrated to Keycloak version >=7.0.1, make sure to set the client’s accessType to public.
*Make sure that keycloak is running before running this app on ng serve. This project is calling keycloak from port 8380, you may want to change that to 8080 if you deploy keycloak as default (src/environments/environment.ts).