Search code examples
javahttpjwtjjwt

how to create exceptions to JWT filter based on URLs


I am working on JWT authentication.I want to bypass ( not allow to pass through jwt filter), the provided URLs. Below is the code snippet.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors().and().csrf().disable().authorizeRequests().antMatchers(bypassURLs)
                    .permitAll().anyRequest().authenticated().and().addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtConfigProperties))
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);}

In the above code, I want the system Not to filter for bypassURLs. If I am passing "/sayHello", then JWTAuthenticationFilter should not be applied to this while the URLs other than "/sayHello" must pass through the JWTAuthenticationFilter.

I have tried http.csrf().ignoringAntMatchers("/sayHello"); and some some regex but not succeded. Please help.


Solution

  • When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

    What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/v1/signup");
    }
    

    And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.