0

I am required to perform some pre-task whenever few specific endpoints are hit in my spring based web app. I came across the interceptor component provided by the spring-security framework. I searched various forums but didn't find relevant answers for configuring and adding interceptor.

Consider a situation where I am required to set some key=value in a database by sending POST request in the database whenever the user hits following endpoints.

/endpoint1 /endpoint2 /endpoint3 /endpoint4

After completion of the pre-task user should be redirected to the origin endpoint.

How can this be achieved using an interceptor in the spring-security framework?

1 Answers1

0

Spring Security is for security stuff related to Authentification and Authorization. You can trigger some action if somebody logged in, but if you just need to trigger action for each request than Spring Security is not a good place for that (according to business logic), better add just filter. Anyway answering to your question:

The best way is to add custom filter to Spring Security Filter Chain: You have to overwrite:

@Configuration
public class CustomWebSecurityConfigurerAdapter
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(
          new CustomFilter(), BasicAuthenticationFilter.class);
    }
} 

and create your custom filter:

public class CustomFilter extends GenericFilterBean {

    @Override
    public void doFilter(
      ServletRequest request, 
      ServletResponse response,
      FilterChain chain) throws IOException, ServletException {
        //your logic here
        chain.doFilter(request, response); //it's needed to pass your request father
    }
}

Code taken from baeldung.com see for more information

Andrew Sasha
  • 1,254
  • 1
  • 11
  • 21
  • How to configure the custom filter to perform pre-tasks? Do In need to configure it as a bean in the XML file wiring the endpoints? Thanks for replying. –  Jan 11 '19 at 11:11
  • Each operation before `chain.doFilter(request, response);` are pre-operation, each operation after post-operation. There is no need to configuring it as a bean, but you can. https://stackoverflow.com/questions/4122870/what-is-the-use-of-filter-and-chain-in-servlet – Andrew Sasha Jan 11 '19 at 13:02