SecurityFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) request; if (skipPattern != null && servletRequest.getRequestURI() != null && servletRequest.getRequestURI().equals(skipPattern)) { chain.doFilter(request, response); return; } String cookieValue = findAuthCookie((HttpServletRequest) request); if (cookieValue == null) { HttpServletResponse servletResponse = (HttpServletResponse) response; servletResponse.sendRedirect(loginUrl); } else { request.setAttribute(LOGGED_USER, getUserName(cookieValue)); chain.doFilter(request, response); } }  @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); @Value("${login.url}") void setLoginUrl(String loginUrl); @Value("${cookie.prefix}") void setCookiePrefix(String cookiePrefix); @Value("${skip.security.pattern}") void setSkipSecurityFilter(String skipPattern); static final String LOGGED_USER; }
@Test public void shouldRedirectToLoginWhenEmptyCookies() throws IOException, ServletException { filter.doFilter(request, response, chain); assertEquals(LOGIN_URL, response.getRedirectedUrl()); }
@Test public void shouldRedirectToLoginWhenNoProperCookie() throws IOException, ServletException { request.setCookies(new Cookie("bla-bla", "123")); filter.doFilter(request, response, chain); assertEquals(LOGIN_URL, response.getRedirectedUrl()); }
@Test public void shouldPassWhenCookieSet() throws IOException, ServletException { request.setCookies(new Cookie(COOKIE_PREFIX+"bla-bla", "vasya|123|lalala")); filter.doFilter(request, response, chain); assertEquals("vasya", request.getAttribute("logged.user")); assertSame(request, chain.getRequest()); }
@Test public void shouldDecodeWhenCookieSet() throws IOException, ServletException { request.setCookies(new Cookie(COOKIE_PREFIX+"bla-bla", "admin%7C1351112621%7C0cbfe5d7f672b17cd945dc65206b7833.war")); filter.doFilter(request, response, chain); assertEquals("admin", request.getAttribute("logged.user")); assertSame(request, chain.getRequest()); }