class BasicAuthSecurityFilter implements Filter {

    @Override
    public void doFilter(final ServletRequest _request,
                         final ServletResponse _response,
                         final FilterChain chain) throws IOException, ServletException {

        final HttpServletRequest request = (HttpServletRequest) _request;
        final HttpServletResponse response = (HttpServletResponse) _response;

        if (isExceptionPath(request)) {
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = request.getSession(false);
        final User user = authenticationService.getUser();
        try {
            if (user == null) {
                if (authenticate(request)) {
                    chain.doFilter(request,
                                   response);
                    if (response.isCommitted()) {
                        authenticationService.logout();
                    }
                } else {
                    challengeClient(request,
                                    response);
                }
            } else {
                chain.doFilter(request,
                               response);
            }
        } finally {
            // invalidate session only when it did not exists before this request,
            // it was created as part of this request and filter is configured to invalidate.
            if (session == null && invalidate) {
                session = request.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
            }
        }
    }

}