Since the Keycloak.js library is in charge of handling authentication and redirecting the user between Keycloak’s login UI and your application, it always needs to run first.
This is how Keycloak handles authentication:
- Keycloak.js is loaded and run in your application.
- Keycloak checks if the user is authenticated.
- If not, it redirects the user to Keycloak’s login interface.
- On success, it redirects the user back to your application.
This happens on every page refresh so we need to handle authentication first and only after that manually bootstrap Angular.
If you’ve previously “auto-bootstrapped” Angular in your index.html file with
ng-app="yourApp", go ahead and remove the line.
Then initialize Keycloak:
I’d also recommend you create a simple wrapper for the global
variable to keep your code more modular and easier to refactor in the future:
Now you can inject
keycloak whenever you need to access your Keycloak state,