每当在基于spring的Web应用程序中碰到几个特定的端点时,我都需要执行一些预任务。我遇到了spring-security框架提供的拦截器组件。我搜索了各种论坛,但没有找到与配置和添加拦截器相关的答案。
考虑一种情况,当用户点击以下端点时,需要通过在数据库中发送POST请求来设置数据库中的key=value
。
/endpoint1
/endpoint2
/endpoint3
/endpoint4
完成任务前的用户应重定向到原始端点。
如何在spring-security框架中使用拦截器来实现这一目标?
答案 0 :(得分:0)
Spring Security用于与认证和授权有关的安全性内容。如果有人登录,则可以触发某些操作,但是如果只需要为每个请求触发操作,那么Spring Security并不是一个合适的选择(根据业务逻辑),add just filter更好。无论如何回答您的问题:
最好的方法是将自定义过滤器添加到Spring Security过滤器链: 您必须覆盖:
@Configuration
public class CustomWebSecurityConfigurerAdapter
extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(
new CustomFilter(), BasicAuthenticationFilter.class);
}
}
并创建您的自定义过滤器:
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//your logic here
chain.doFilter(request, response); //it's needed to pass your request father
}
}