How to disable or override RequestCacheAwareFilter in Spring Boot
Asked Answered
V

3

6
  1. I have very basic simple Spring Boot Rest application.
  2. I needed to implement custom authentication in Spring Security: for every REST request I need to check username and password, that are in specific headers of every request ("username" and "password").

  3. So I implemented custom AuthEntryPoint:

     @Service
    public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
            String username = httpServletRequest.getHeader("username");
            String password = httpServletRequest.getHeader("password");
            if (!username.equals("admin") || !password.equals("admin")) {
                throw new RuntimeException("", new BadCredentialsException("Wrong password"));
            }
        }
    }
  4. So, I realized, that RequestCacheAwareFilter is caching first request and headers are also stored in cache. So if I make a request with wrong pass and then with right one, I will still get an exception.

So, how could I override the CacheAwareFilter or disable it? Or am I doing something totally wrong?

Vain answered 6/11, 2015 at 13:44 Comment(1)
I just made the app stateless like here: #2505090 And now everything is okay.Vain
F
10

Use custom WebSecurityConfigurerAdapter to set request cache to NullRequestCache:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestCache()
            .requestCache(new NullRequestCache());
    }
}
Fyke answered 4/2, 2016 at 10:20 Comment(1)
Can be done quicker (using Spring Security 5.2.1): http.requestCache().disable()Tinge
V
1

I just made the app stateless like here: How can I use Spring Security without sessions?

And now everything is okay.

Vain answered 6/11, 2015 at 17:15 Comment(0)
P
0

In Spring Security 6:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
        .requestCache(RequestCacheConfigurer::disable)
        .build();
}
Perplexed answered 3/10, 2023 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.