50

我想为每个请求接收一些信息,所以我认为与其为每个请求提供一个函数并分别从请求中获取这些信息,不如有一个过滤器。
所以每个请求都应该通过那个过滤器,我就会得到我想要的。


问题是:如何编写自定义过滤器?
假设它不像任何预定义的弹簧安全过滤器,它是全新的。

4

2 回答 2

47

您可以使用标准的 Java 过滤器。只需将它放在 web.xml 中的身份验证过滤器之后(这意味着它将在过滤器链中稍后并在安全过滤器链之后调用)。

public class CustomFilter implements Filter{

    @Override
    public void destroy() {
        // Do nothing
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {

            HttpServletRequest request = (HttpServletRequest) req;

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            if (roles.contains("ROLE_USER")) {
                request.getSession().setAttribute("myVale", "myvalue");
            }

            chain.doFilter(req, res);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // Do nothing
    }

}

web.xml 的片段:

<!-- The Spring Security Filter Chain -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Your filter definition -->
<filter>
    <filter-name>customFilter</filter-name>
    <filter-class>com.yourcompany.test.CustomFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>customFilter</filter-name>
    <url-pattern>/VacationsManager.jsp</url-pattern>
</filter-mapping>

您还可以添加成功登录后将调用的处理程序(您需要扩展SavedRequestAwareAuthenticationSuccessHandler)。看看这里如何做到这一点。我认为这是一个更好的主意。


更新:
或者您可以在安全过滤器的末尾使用此过滤器,如下所示:

<security:filter-chain-map>
    <sec:filter-chain pattern="/**"
            filters="
        ConcurrentSessionFilterAdmin, 
        securityContextPersistenceFilter, 
        logoutFilterAdmin, 
        usernamePasswordAuthenticationFilterAdmin, 
        basicAuthenticationFilterAdmin, 
        requestCacheAwareFilter, 
        securityContextHolderAwareRequestFilter, 
        anonymousAuthenticationFilter, 
        sessionManagementFilterAdmin, 
        exceptionTranslationFilter, 
        filterSecurityInterceptorAdmin,
        MonitoringFilter"/> <!-- Your Filter at the End -->
</security:filter-chain-map>

并有你的过滤器,你可以使用这个:

public class MonitoringFilter extends GenericFilterBean{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    //Implement this Function to have your filter working
}
于 2012-08-13T06:27:19.087 回答
15

只是把这个混在一起;如何使用custom-filter内部http元素:

<security:http auto-config="false" ...>
  ...
  <security:custom-filter position="FORM_LOGIN_FILTER" ref="MyCustomFilter" />
</security:http>
于 2015-01-05T17:33:49.447 回答