I'm trying to setup Spring Security to work with Keycloak 21 but unfortunately most of the tutorials on Internet are outdated. I configured client and realms into Keycloak but Spring security is not clear what should be. I tried the code from this link:
I added these gradle dependencies:
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client:3.1.0'
implementation 'org.springframework.boot:spring-boot-starter-security:3.1.0'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.1.0'
and this yml config:
spring:
security:
oauth2:
client:
provider:
keycloak:
issuer-uri: https://ip/realms/admin_console_realm
registration:
keycloak-login:
authorization-grant-type: authorization_code
client-name: My Keycloak instance
client-id: admin_console_client
client-secret: qwerty
provider: keycloak
scope: openid,profile,email,offline_access
resourceserver:
jwt:
issuer-uri: https://ip/realms/admin_console_realm
jwk-set-uri: https://ip/realms/admin_console_realm/protocol/openid-connect/certs
It's not clear what I need to add as a Spring security configuration here:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeHttpRequests()
.requestMatchers("/*").hasAuthority("ROLE_TECH_SUPPORT")
.anyRequest().authenticated()
.and()
.oauth2Login();
return httpSecurity.build();
}
}
I added the role into Keycloak client:
When I open a Rest API link into the browser I'm redirected to Keycloak's login page. After successful authentication I get:
Access to ip was deniedYou don't have authorization to view this page.
HTTP ERROR 403
Do you know how I can fix this issue?