-
Notifications
You must be signed in to change notification settings - Fork 5
Getting Started
To add Keycloak security to your Angular CLI application, you will need two things:
- A Keycloak server where your users will be managed.
- The keycloak-schematic package.
There are three methods to install/access the Keycloak Server
- Ordinary Download (requires java)
- Docker image
- Cloud-based/OpenShift
If you are using OpenShift, it's easy to spin up a Keycloak server in the cloud and use it for development. But for the rest of this documentation, we will assume you used one of the first two methods and you have an instance of Keycloak running locally on port 8080. If you need help with server installation, see the Keycloak Getting Started Guide.
At this point you should have a Keycloak server running on localhost:8080 with at least one user defined. Go to the root of your Angular CLI application and follow these steps:
npm install -g @ssilvert/keycloak-schematicng generate keycloak --collection @ssilvert/keycloak-schematic --clientId=<clientName>
Where clientId is just the name of your application.
The keycloak-schematic installs files and services to your application. It also replaces your main.ts file. Don't worry. Your old main.ts is backed up to main.ts.no-keycloak.
Now you need to let the Keycloak Server know about your Angular CLI application. When you ran the keycloak-schematic, it installed a file called client-import.json into the root directory of your Angular CLI application. Follow these steps:
- Log in to the Keycloak Admin Console
- Click on "Clients"
- Click "Create"
- Click "Select file"
- Choose your
client-import.jsonand click "Save" - Log out of the Keycloak Admin Console
Warning: In production, it is very important to make sure the redirect URIs you have configured for the client are correct and as specific as possible. The redirect URI from client-import.json is very permissive.
With your browser logged out of the Keycloak Server, build and run your application.
ng serve
Go to http://localhost:4200/. You should be greeted by the Keycloak login screen. Your application is now secured by Keycloak! (if you don't see the login screen it might be because you are still logged in to the Keycloak server. Keycloak knows if you are already logged in!)
Need to log out? You just need to add a logout button to your page. See Login & Logout Buttons for instructions.
If you go back to the Keycloak Admin Console, you won't need to log in. That's because Keycloak handles single signon automatically. If you then log out of the Keycloak Admin Console, you will be logged out of your Angluar CLI application as well.