如何在春季安全编写自定义filter?
我希望每个请求都能得到一些信息,所以我认为不是每个请求都有一个函数,而是分别从请求中获取这些信息, 最好是有一个filter。
所以每一个请求都要通过这个filter,我得到我想要的。
问题是:如何编写自定义filter?
假设它不像任何预定义的弹簧安全filter,它是全新的。
您可以使用标准的Javafilter。 只需将其放置在web.xml中的authenticationfilter之后(这意味着它将在后面的filter链中并在安全filter链之后被调用)。
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>
你也可以添加处理程序,将成功login后调用(您需要扩展SavedRequestAwareAuthenticationSuccessHandler )。 看看这里如何做到这一点。 我认为这是一个更好的主意。
更新:
或者你可以在你的安全filter的最后有这样的filter:
<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>
并有你的filter,你可以使用这个:
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 }
把这个混在一起吧 如何使用http
元素内的custom-filter
:
<security:http auto-config="false" ...> ... <security:custom-filter position="FORM_LOGIN_FILTER" ref="MyCustomFilter" /> </security:http>