我想設置一個引用cookie,因爲我需要排除某些頁面(例如錯誤,登錄,註銷等),以便能夠重定向到上次調用但未排除的頁面登錄後:在Spring Security Filter Chain之前設置Cookie
public class CookieReferrerFilter extends OncePerRequestFilter {
public static final String REFERRER_COOKIE_NAME = "REFERRER";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (!isReferrerExcluded(request)) {
Cookie sessionCookie = new Cookie(REFERRER_COOKIE_NAME, request.getRequestURI());
sessionCookie.setPath(!"".equals(request.getContextPath()) ? request.getContextPath() : "/");
sessionCookie.setSecure(false);
sessionCookie.setMaxAge(-1);
response.addCookie(sessionCookie);
}
filterChain.doFilter(request, response);
}
private boolean isReferrerExcluded(HttpServletRequest request) {
for (String pattern : EXCLUDED_REFERRER) {
if (new AntPathRequestMatcher(pattern).matches(request)) {
return true;
}
}
return false;
}
}
但是Spring Security Filter鏈在CookieReferrerFilter之前被觸發。 因此,調用受保護的頁面會立即將我重定向到登錄頁面,而無需在之前調用CookieReferrerFilter.doFilterInternal
,也不設置cookie。
有一類配置webbapp(設置配置類,映射,過濾器)延伸AbstractAnnotationConfigDispatcherServletInitializer
:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationContextConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
CookieReferrerFilter cookieReferrerFilter = new CookieReferrerFilter();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] { cookieReferrerFilter, characterEncodingFilter };
}
}
,另一個簡單地延伸AbstractSecurityWebApplicationInitializer
:
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
[安全過濾鏈](http://docs.spring.io/spring-security/site/docs/3.0.x/reference/security-filter-chain.html) – 2014-12-19 08:32:35