Complete Authentication Flow
The end-to-end process is seamless:
A user accesses the Angular web application.
The app redirects to the Keycloak instance on Cloud Run for login.
The user authenticates.
Keycloak issues a JWT and redirects back to Angular.
Angular includes this JWT in the Authorization header of an API call to the Spring Boot backend.
The Spring Boot application validates the JWT against Keycloak and, if valid, processes the request and returns the secured data.
Keycloak on Google Cloud Run
Hosting Keycloak on Google Cloud Run provides a fully managed, serverless environment that automatically scales based on traffic, even scaling down to zero to minimize costs. For this setup, Keycloak is containerized and requires a persistent database backend, such as Google Cloud SQL (e.g., PostgreSQL), to store realm configurations, users, and session data. Cloud Run handles HTTPS termination and can be configured with a custom domain for a professional user-facing URL.
Spring Boot Backend (Resource Server)
The Spring Boot backend is configured as a resource server, responsible for protecting API endpoints.
Configuration: Integration is streamlined and configured with the Keycloak issuer URI
Token Validation: When the backend receives a request with a JWT, the Spring Security filter chain automatically:
Validates the token's signature against the public keys fetched from Keycloak's JWKS (JSON Web Key Set) URI.
Checks the token's expiration (exp) and issuer (iss).
Authorization: Endpoint security is managed by spring.
Spring Security parses the roles and permissions from the JWT's claims and enforces access control, ensuring only authenticated and authorized users can access specific resources.
Angular Frontend Integration
The Angular application integrates with Keycloak using an OpenID Connect (OIDC) compliant library.
The typical authentication flow is as follows:
Initialization: The Angular app is configured with the Keycloak server URL, realm, and client ID.
Authentication: When a user tries to access a protected route, the app redirects them to the Keycloak login page hosted on Cloud Run.
Token Retrieval: After successful authentication, Keycloak redirects the user back to the Angular app with an access token and a refresh token in the URL fragment.
Token Management: The keycloak-angular library securely stores these tokens. The access token, a JSON Web Token (JWT), is automatically attached as a Bearer token in the Authorization header for all subsequent API requests to the Spring Boot backend.