Search code examples
javaspringspring-mvcspring-bootbasic-authentication

Spring Boot, filter is not getting restricted to specific url


In the spring-boot app, I have created few API calls. I want to add a filter only for few urls. The security config is as follows:

@Configuration
@EnableWebMvc
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class)
            .authorizeRequests().anyRequest().denyAll();

        http.authorizeRequests().antMatchers("/api/user").permitAll();

    }

    AuthenticationFilter authenticationFilter() throws Exception
    {
        AuthenticationFilter filter = new AuthenticationFilter();
        return filter;
    }
}

I don't want filter to be applied for any api call except /api/user , so I denied for all urls and permitted for /api/user.

AuthorizationFilter class is as follows:

public class AuthenticationFilter extends OncePerRequestFilter
{

    public AuthenticationFilter()
    {
        super();
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
    {
        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            System.out.println("headerName " + headerName);
            System.out.println("headerVal " + request.getHeader(headerName));
        }
        chain.doFilter(request,response);
    }
}

This just prints all header information. Currently it is printing header information on all api calls but I want this to be printed only in case of /api/user and not on any other api call. Please suggest what changes shall I made?


Solution

  • Got a working solution

    @Configuration
    @EnableWebSecurity
    public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**");
            // add security constraints for /api/... here
        }
    
        /* rest of config */
    }
    

    How to ignore Spring Security config for every thing except a pattern