ClientIdFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); String servletPath = request.getServletPath(); if (servletPath != null && servletPath.endsWith("authorize")) { if (currentAuthentication != null && currentAuthentication.getDetails() instanceof SAMLUser) { if (!isBlackHole(request)) { SecurityContextHolder.clearContext(); request.getSession().setAttribute(BLACK_HOLE_ATTRIBUTE, Boolean.TRUE); } else { request.getSession().removeAttribute(BLACK_HOLE_ATTRIBUTE); } } else { request.getSession().setAttribute(BLACK_HOLE_ATTRIBUTE, Boolean.TRUE); } } String clientId = request.getParameter("client_id"); if (currentAuthentication != null && currentAuthentication.getDetails() instanceof SAMLUser) { SAMLUser samlUser = SAMLUser.class.cast(currentAuthentication.getDetails()); if (StringUtils.hasText(clientId) && !samlUser.getClientId().equals(clientId)) { SecurityContextHolder.clearContext(); } } chain.doFilter(servletRequest, response); }  @Override void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain); static final String BLACK_HOLE_ATTRIBUTE; }
@Test public void clearAuthenticationOnClientIdChange() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("client_id", "oidc"); setAuthentication(); subject.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNull(SecurityContextHolder.getContext().getAuthentication()); }
@Test public void doNotClearAuthenticationOnNewLogin() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/authorize"); subject.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); boolean isBlackHole = Boolean.class.cast(request.getSession().getAttribute(BLACK_HOLE_ATTRIBUTE)).booleanValue(); assertTrue(isBlackHole); setAuthentication(); subject.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNull(request.getSession().getAttribute(BLACK_HOLE_ATTRIBUTE)); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); }
@Test public void clearAuthenticationWhenReAuthenticating() throws Exception { setAuthentication(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/authorize"); subject.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNull(SecurityContextHolder.getContext().getAuthentication()); setAuthentication(); subject.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); }