In some cases, such as troubleshooting, security checks can cause obstacles for us, but I cannot quickly turn them off. I must remove @EnableWebSecurity and @EnableMethodSecurity, recompile the project, and put it on the server before troubleshooting.
After adding @EnableWebSecurity and @EnableMethodSecurity, I customized parameters in the configuration file to disable SpringSecurity. However, SpringSecurity no longer validates my token, but @PreAuthorize is still working. Here is the code.
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationConverter converter) throws Exception {
if (officeSecurityProperties.isEnable()) {
http.authorizeHttpRequests(
authorize -> authorize
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(
oauth2 -> oauth2.jwt(
jwt -> jwt.jwtAuthenticationConverter(converter)
)
);
} else {
http.securityContext(AbstractHttpConfigurer::disable);
}
return http.build();
}
>Solution :
There are two things you could consider.
Don’t Enable
The easiest way is to not enable things from the beginning. You can disable the Spring Boot configuration and then publish your own configuration class with a @ConditionalOnProperty annotation like so:
@SpringBootApplication(exclude=SecurityAutoConfiguration.class)
// ... main class
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@ConditionalOnProperty("office.security.property")
public SecurityConfiguration {
// ...
}
Programmatically Enable
It’s trickier to turn something off that you’ve already turned on. You appear to already have something working for web security. For method security, change your annotation to:
@EnableMethodSecurity(prePostEnabled = false)
public SecurityConfig {
}
And then publish the method interceptors on your own like so:
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnProperty("office.security.property")
static MethodInterceptor preAuthorizeAuthorizationMethodInterceptor() {
return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
}
This will publish @PreAuthorize support. You would publish a method interceptor for each annotation that you want to enable the behavior for.