我只想保护几个特定的端点,如果有任何请求到达受保护的端点,我想对其应用过滤器。
这是我到目前为止所尝试的:
http
.csrf().disable()
.addFilterAfter((Filter) MyFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/api/users").permitAll()
.anyRequest().authenticated();
我希望它只保护/api/users
如果任何请求到达这个受保护的端点,那么它应该通过过滤器。但是现在每个请求都要经过过滤器。
请建议怎么做才是正确的。
在过滤器中创建一个RequestMatcher
,并使其仅适用于匹配的请求。
public class MyFilter implements Filter {
private RequestMatcher requestMatcher = new AntPathRequestMatcher("/api/users");
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
if (!this.requestMatcher.matches(request)) {
// the request do not match, do nothing but continue the filter chain
chain.doFilter(request, response);
return;
}
// do the filter logic
}
}