[Resolved] Spring boot JWT Filter called twice

[Resolved] Spring boot JWT Filter called twice

[Resolved] Spring boot JWT Filter called twice:

Recently when I was integrating JWT Filter and Simple CORS filter in my spring boot project, I observed that both the filters are called twice before actually reaching my servlet/rest controller.

 

After googling, I got this link,

As per that,

One invocation is by servlet container and the other is by Spring Security, so the filter will get called twice. So by adding this line in your JWT Filter bean implementation registrationBean.setEnabled(false); only the spring security calls for token, so JWT filter call twice issue will get resolved.

 

Issue Code: [Called twice]

@Bean
public FilterRegistrationBean jwtFilter(){
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}

 

 

Working code: [Calling only once]

@Bean
public FilterRegistrationBean jwtFilter(){
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/*");
// set as false to avoid multiple filter calls
registrationBean.setEnabled(false);
return registrationBean;
}

 

You can also try these below ways to resolve the same issue:

  1. Make sure you are calling the delete request from your angular side properly.

It should be

return this.http.delete(url, {headers:headerValues});

Not,

return this.http.delete(url, JSON.stringify(imageName), {headers:headerValues});

 

Only post method takes the request body, where as delete takes in the URI only.

 

 

2. Add the below in your filter responses (mostly in cors filter)


response.setHeader("Access-Control-Expose-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

along with,


response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

 

3. Add the configuration to your spring boot main class


@Configuration
public static class PathMatchingConfigurationAdapter extends WebMvcConfigurerAdapter {

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}

 

4. Add content-type:application/json to your request method and try.

 

 

Hope it helps someone!

 

 

 

 

610 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *