0

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?

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66
  • and you could just make this more springly defining a @Component in the filter and autowiring it in your SecurityConfig :-) – Hinotori Sep 29 '16 at 19:58

1 Answers1

0

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

Community
  • 1
  • 1
Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66