Issue
I have created two custom filters, one responsible for validating JWT and one for handling ExpiredJwtException
.
I have found solution to invoke them in the right order there: href="https://stackoverflow.com/questions/53238234/multiple-spring-security-filters">Multiple Spring Security filters, so that the ExpiredJwtException
is properly caught:
http.antMatcher("jwtRequestFilter/exceptionHandlerFilter/**")
.addFilterBefore(exceptionHandlerFilter, FilterSecurityInterceptor.class)
.antMatcher("jwtRequestFilter/**")
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
After some refactoring it turned out that all I need to make it work is:
http.antMatcher("jwtRequestFilter/**")
.addFilterBefore(exceptionHandlerFilter, FilterSecurityInterceptor.class)
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
But I don't get how does the antMatcher
method work here. Either antMatcher("jwtRequestFilter/exceptionHandlerFilter/**")
or antMatcher("jwtRequestFilter/**")
is needed to remain correct order.
How does expressions in antMatcher
work? Does **
means other filters in the chain and jwtRequestFilter
on the beginning of the expression means it is last filter?
Solution
The antMatcher
method will match the path of incoming requests, it is not related to the names of the filters.
From the Javadoc for antMatcher
:
Allows configuring the HttpSecurity to only be invoked when matching the provided ant pattern.
This means that your custom filters (and the rest of the filter chain) will only be invoked if the incoming request matches the ant pattern that you have provided.
Consider this example
http
.antMatcher("/admin/**")
.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class)
// ...
If you make a request to GET "/admin/home", then HttpSecurity
will be invoked the request will be processed by customFilter.
If you make a request to GET "/user/home", then HttpSecurity
will not be invoked the request won't be processed by customFilter.
To understand how ant-style path matching works, see the Javadoc for AntPathMatcher.
Answered By - Eleftheria Stein-Kousathana
Answer Checked By - Katrina (JavaFixing Volunteer)