In my Spring-Boot Application (Resource Server), I want to skip the token-check against the Authorization Server in some cases. To achieve this, I inserted a filter before the SecurityContextPersistenceFilter in the Spring-Security filter chain.
Ideally, I want things not to be changed when the condition is not met (Authorization Server called, Authentication set according to response). I found out that, while the Security Context gets overwritten when the condition is met, problem occurs when the filter does nothing: In that case, the OAuth2AuthenticationProcessingFilter does not appear at all in the chain and I am left with the "anonymousUser".
Here is what my custom filter looks like:
public class SessionFilter extends GenericFilterBean {
    @Override
    public void doFilter(
        ServletRequest servletRequest,
        ServletResponse servletResponse,
        FilterChain filterChain
    ) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String authorizationHeader = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
        
        if (authorizationHeader != null && meetsCondition(authorizationHeader)) {
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(new CustomAuthentication(authorizationHeader));
            httpRequest.getSession(true)
                    .setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
It gets thrown in the chain using the WebSecurityConfigurerAdapter:
        http  //...
                .and().csrf().disable()
                .addFilterBefore(
                        new SessionFilter(),
                        SecurityContextPersistenceFilter.class
                 );
Is there a way to achieve what I am looking for using this method? I am using Spring-Boot 1.4.7 with Java 8 and Spring-Security 4.1.4 (upgrading is sadly not possible for reasons external to this question).
Sources which I based my code/understanding on:
 
     
    