How to secure a Spring Security client application with OIDC (using pac4j)
If you already have Spring Security in your application, with hasRole rules, @PreAuthorize on services and code reading SecurityContextHolder and you want to add an OpenID Connect login, while keeping that authorization code, you can use pac4j for that. Whatever the provider (Keycloak, Microsoft Entra ID, Okta, a CAS server, etc.), once pac4j has authenticated the user, it can make that user…
To integrate OpenID Connect (OIDC) login into an existing Spring Security application using pac4j, follow these steps:
1. Set up a new Maven project with Java 17 or later and Spring Boot v4.x, which includes Spring Security v7 or Spring Boot v3.x with Spring Security v6. The bridge supports both versions.
2. Create the pom.xml file with Spring Boot parent dependency and specify Java version and project details.
3. Add the necessary Maven dependencies in pom.xml:
- spring-boot-starter-webmvc for MVC support
- spring-boot-starter-security for Spring Security
- org.pac4j:jakartaee-pac4j (version 8.0.4) for the OIDC authentication implementation
- org.pac4j:pac4j-oidc (version 6.5.9) for OpenID Connect support
- org.pac4j:spring-security-pac4j (version 10.1.0) as the bridge to integrate pac4j with Spring Security
4. Configure pac4j by creating a Pac4jConfig.java class annotated with @Configuration. Declare an OidcClient bean with OIDC client configuration and an authorization generator to convert trusted profile attributes into application roles.
5. Ensure your Spring Security application is configured with SpringBootApp.java as the main class.
By following these steps and using the appropriate pac4j artifacts and configuration, you can seamlessly integrate OIDC login into an existing Spring Security application while preserving the existing authorization mechanism.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.