Spring Boot Security, adding filters to different routes

I'm trying to put together a single application that contains both an API and an Admin interface using Spring Boot.

The idea is that all API endpoints will be accessible via domain.com/api/ and the admin interface under domain.com/admin/

The Admin interface and the API need different types of authentication, so somehow in the spring security configuration I need to define a filter for routes starting with /api/ and define another route to be called for routes starting /admin/

This is my security config class, which I thought might work, but it doesn't.

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    AuthenticationFilter authenticationFilter;

    AdminAuthenticationFilter adminAuthenticationFilter;

    protected void configure(HttpSecurity http) throws Exception {

                // Allow anonymous visitors to auth controller methods

                .antMatchers("/admin/**").authenticated().addFilterBefore(adminAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .antMatchers("/api/**").authenticated().addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class)

                // All other request need to be authenticated



Open in new window

Who is Participating?
SheppardDigitalConnect With a Mentor Author Commented:
I managed to resolve this myself.

        http.authorizeRequests().antMatchers("/admin/**").authenticated().and().addFilterBefore(adminAuthFilter, UsernamePasswordAuthenticationFilter.class);

        http.authorizeRequests().antMatchers("/api/**").authenticated().and().addFilterBefore(apiAuthFilter, UsernamePasswordAuthenticationFilter.class);

Open in new window

SheppardDigitalAuthor Commented:
Self resolved
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.