Home > Enterprise >  Extends OncePerRequestFilter bypass specific Url
Extends OncePerRequestFilter bypass specific Url

Time:12-19

i use springboot 2.5.6. I want to skip specific url(/doc.html).

i have created a JwtAuthenticationTokenFilter extends OncePerRequestFilter

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //the logic of authentication
}

And then i create SecurityConfig extends WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web)
            throws Exception {
        web.ignoring()
                .antMatchers(HttpMethod.OPTIONS, "/**")
                .antMatchers("/doc.html");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
           .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/doc.html").anonymous()
                .and()
                .requestMatchers().antMatchers("/doc.html");

but when i access localhost:8080/doc.html, the /doc.html didn't skip;

and i also try to override shouldNotFilter in JwtAuthenticationTokenFilter.java, but it did't work also;

@Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return (
                new AntPathMatcher().match("/doc.html", request.getServletPath()));
    }

CodePudding user response:

Your JwtAuthenticationTokenFilter will be picked up by Spring as a component and will be included in the filter chain and will not be automatically excluded through your SecurityConfig.

So overwriting shouldNotFilter seems like a valid approach and should work as expected.

You could try to use request.getRequestURI() instead of request.getServletPath() in order to ensure to match the actual request path. See this for further details.

CodePudding user response:

You can create a simple array inside JwtAuthenticationTokenFilter if you want to bypass for multiple Urls.

For example:

    private static final String[] excluded_urls = {
            "/login",
            "**/doc.html"
    };

And then override shouldNotFilter method:

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String url = request.getRequestURI();
        return Stream.of(excluded_urls).anyMatch(x -> pathMatcher.match(x, url));
    }

Where

pathMatcher = new AntPathMatcher();
//can be injected or create wherever required
  • Related