如何在Spring Boot中禁用或覆盖RequestCacheAwareFilter

vma*_*nko 2 java spring spring-mvc spring-security spring-boot

  1. 我有一个非常基本的简单Spring Boot Rest应用程序。
  2. 我需要在Spring Security中实现自定义身份验证:对于每个REST请求,我需要检查用户名和密码,这些名称和密码位于每个请求的特定标头(“用户名”和“密码”)中。

  3. 因此,我实现了自定义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"));
            }
        }
    }
    Run Code Online (Sandbox Code Playgroud)
  4. 因此,我意识到RequestCacheAwareFilter正在缓存第一个请求,并且标头也存储在缓存中。因此,如果我通过了错误的通过请求,然后又通过了正确的请求,我仍然会遇到异常。

那么,如何覆盖或禁用CacheAwareFilter?还是我做错了什么?

小智 5

使用自定义WebSecurityConfigurerAdapter将请求缓存设置为NullRequestCache:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestCache()
            .requestCache(new NullRequestCache());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 可以更快地完成(使用 **Spring Security 5.2.1**):`http.requestCache().disable()` (4认同)

vma*_*nko 1

我刚刚将应用程序设置为无状态,如下所示:How can I use Spring Security without session?

现在一切都好了。