How to write a custom filter in spring security?

前端 未结 2 1530
清歌不尽
清歌不尽 2020-11-28 08:11

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 b

2条回答
  •  难免孤独
    2020-11-28 08:40

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

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

    
    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
    
    
    
        springSecurityFilterChain
        /*
    
    
    
    
        customFilter
        com.yourcompany.test.CustomFilter
    
    
        customFilter
        /VacationsManager.jsp
    
    

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


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

    
         
    
    

    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
    }
    

提交回复
热议问题