'Custom Filter Authentication using Spring Security

I'm trying to implement my own authentication filter so it checks if user is authenticated. I'm using a filter as I see in Internet docs

public class CustomAuthenticationFilter implements Filter {

    private static final Log LOG = LogFactory.getLog(CustomAuthenticationFilter.class);

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

    
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    
        // CREATE AUTHENTICATION OBJECT (with Entered Username & Password)
        // EXCEPTION (IOException)  if fail
        UsernamePasswordAuthenticationToken authRequest = null;
        authRequest = new UsernamePasswordAuthenticationToken(request, response);

        Authentication authentication = authRequest;

        if (authentication.isAuthenticated()) {
            LOG.info("Authenticated user: ");
            // When they are present we authenticate the user in the SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(authentication);

            chain.doFilter(request, response);
        } else {
            LOG.info("User isn't authenticated");
            //chain.doFilter(request, response);
        }
    }
}

My security configuration as follow:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories(basePackageClasses = UsersRepository.class)
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    private static final Log LOG = LogFactory.getLog(SecurityConfiguration.class);

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    UrlAuthenticationSuccessHandler urlAuthenticationSuccessHandler;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //http.addFilterAfter(new CustomAuthenticationFilter(), BasicAuthenticationFilter.class);

        http.csrf().disable();
        http.headers().cacheControl();

        http.headers().frameOptions().disable()
                .addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "ALLOW-FROM mydomain.com"));

        http.authorizeRequests().antMatchers("/dashboard/**").authenticated().and().formLogin().loginPage("/login")
                .permitAll().usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/loginsuccess").permitAll().successHandler(urlAuthenticationSuccessHandler).and()
                .logout().permitAll().and().authorizeRequests().antMatchers("/assets/**").permitAll();

        // http.addFilterBefore(new CustomAuthenticationFilter(),
        // BasicAuthenticationFilter.class);

    }

    private PasswordEncoder getPasswordEncoder() {

        return new BCryptPasswordEncoder();
    }
}

I tried:

http.addFilterAfter
http.addFilterBefore

but FIRST TIME is not authenticated so it stops.

if I comment:

chain.doFilter(request, response);

works, but I never get the authenticated user.

Any idea?? thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source