spring 我希望JWT过滤器只用于指定的url模式(管理服务url),而不是用于Sping Boot Security中的所有url

xoshrz7s  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(92)

我希望过滤以“/api/**”开头端点URL,但customJwtAuthenticationFilter会过滤所有其他URL。

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/users","/api/users").authenticated()
            .anyRequest().permitAll()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().exceptionHandling().accessDeniedPage("/403").authenticationEntryPoint(jwtAuthenticationEntryPoint).and().
            formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/users")
            .failureUrl("/login?error=true")
            .permitAll()
            .and()
            .logout().logoutSuccessUrl("/").permitAll()
          .and().addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

好心帮忙?
提前致谢

jv2fixgn

jv2fixgn1#

如果您只想筛选路径为/api/**url,则可以使用类AbstractAuthenticationProcessingFilter来扩展类CustomJwtAuthenticationFilter并且可以使用类RequestMatcher跳过该url路径例如

class CustomJwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter{
    public CustomJwtAuthenticationFilter(RequestMatcher matcher){
        super(matcher);
    }
}

并且对于类RequestMatcher,

class SomeRequestMatcher implements RequestMatcher {
    @Override
     public boolean matches(HttpServletRequest request) {
     OrRequestMatcher skipRequestMatcher = new OrRequestMatcher(List.of("/api/**").stream().map(p-> new AntPathRequestMatcher(p))
            .collect(Collectors.toList()));

    if(skipRequestMatcher.matches(request))
        return false;
    return true;
  }
}

相关问题