如何在 Spring Security 中编写自定义过滤器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11928637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:18:31  来源:igfitidea点击:

How to write a custom filter in spring security?

springfilterspring-security

提问by Matin Kh

I want to receive some information per request, so I think instead of having a function for each request and obtaining those information from requests separately, it's better to have a filter.
So every request shall pass that filter and I gain what I want.


The question is: How can I write a custom filter?
Suppose it is not like any predefined spring security filters and it is totally new.

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


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

采纳答案by dimas

You can use the standard Java filter. Just place it after authentication filter in web.xml (this means that it will go later in the filter chain and will be called after security filter chain).

您可以使用标准 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
    }

}

Fragment of web.xml:

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>

Also you can add handler that will be invoked after successfull login (you need to extend SavedRequestAwareAuthenticationSuccessHandler). Look herehow to do this. And I think that this is even better idea.

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



UPDATED:
Or you can have this filter at the end of your security filters like this:

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

<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>

And to have your filter, you may use this:

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

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
}

回答by Ithar

Just throwing this in the mix; how about using custom-filterinside httpelement:

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

<security:http auto-config="false" ...>
  ...
  <security:custom-filter position="FORM_LOGIN_FILTER" ref="MyCustomFilter" />
</security:http>