Site icon NgDeveloper

[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;
}

Other ways to resolve the JWT Filter called twice issue:

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.

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");

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);
}
}

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

That’s all.

Feel free to follow us on twitter!

Exit mobile version