Spring Security Adapter
To to secure an application with Spring Security and Keyloak, add this adapter as a dependency to your project.
You then have to provide some extra beans in your Spring Security configuration file and add the Keycloak security
filter to your pipeline.
Unlike the other Keycloak Adapters, you should not configure your security in web.xml. However, keycloak.json is still required.
Adapter Installation
Add Keycloak Spring Security adapter as a dependency to your Maven POM or Gradle build.
org.keycloak
keycloak-spring-security-adapter
&project.version;
]]>
Spring Security Configuration
The Keycloak Spring Security adapter takes advantage of Spring Security's flexible security configuration syntax.
Java Configuration
Keycloak provides a KeycloakWebSecurityConfigurerAdapter as a convenient base class for creating a
WebSecurityConfigurer
instance. The implementation allows customization by overriding methods. While its use is not required, it greatly simplifies your security context configuration.
You must provide a session authentication strategy bean which should be of type
RegisterSessionAuthenticationStrategy
for public or confidential applications and
NullAuthenticatedSessionStrategy
for bearer-only applications.
Spring Security's SessionFixationProtectionStrategy
is currently not supported because it changes
the session identifier after login via Keycloak. If the session identifier changes, universal log out will not
work because Keycloak is unaware of the new session identifier.
XML Configuration
While Spring Security's XML namespace simplifies configuration, customizing the configuration can be a bit
verbose.
]]>
Naming Security Roles
Spring Security, when using role-based authentication, requires that role names start with ROLE_
.
For example, an administrator role must be declared in Keycloak as ROLE_ADMIN
or similar, not simply
ADMIN
.
Client to Client Support
To simplify communication between clients, Keycloak provides an extension of Spring's RestTemplate
that
handles bearer token authentication for you. To enable this feature your security configuration must add the
KeycloakRestTemplate
bean. Note that it must be scoped as a prototype to function correctly.
For Java configuration:
For XML configuration:
]]>
Your application code can then use KeycloakRestTemplate
any time it needs to make a call to another
client. For example:
getProducts() {
ResponseEntity response = template.getForEntity(endpoint, String[].class);
return Arrays.asList(response.getBody());
}
}
]]>
Spring Boot Configuration
Spring Boot attempts to eagerly register filter beans with the web application context. Therefore,
when running the Keycloak Spring Security adapter in a Spring Boot environment, it may be necessary to add two
FilterRegistrationBean
s to your security configuration to prevent the Keycloak filters from being
registered
twice.