Reputation: 344
I am using Keycloak to authenticate my spring boot application,
I have create a new realm (CommonServices) with a client (chatting-system)
I have this configuration
keycloak:
auth-server-url: http://localhost:8083/auth
realm: CommonServices
resource: chatting-system
public-client: true
principal-attribute: preferred_username
use-resource-role-mappings: true
security-constraints[0].authRoles[0]: user
ssl-required: external
spring:
data:
mongodb:
host: localhost
port: 27017
database: Chat
username: saga
password: password
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:8083/auth/realms/CommonServices/protocol/openid-connect/certs
issuer-uri: http://localhost:8083/auth/realms/CommonServices
and I have configured the security as such:
@KeycloakConfiguration
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/**")
.hasRole("user")
.anyRequest()
.authenticated();
}
}
@Configuration
public class KeycloakConfig {
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}
THE ISSUE
when I access my GET api everything goes fine but
if I access the POST rest API I get 403 forbidden
Upvotes: 1
Views: 4851
Reputation: 2626
I guess that's a problem with CSRF
protection that Spring Security
enables by default. Try disabling it in your SecurityConfig
to make sure that's the case.
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.csrf().disable() // <- THIS LINE
.authorizeRequests()
.antMatchers("/**")
.hasRole("user")
.anyRequest()
.authenticated();
}
If that's the reason, I recommend to set up proper CSRF protection, as disabling it is time saving in terms of development, but overall is not a good idea in terms of deploying to production.
Upvotes: 9