Игнорирование WebSecurity не работает с AbstractAuthenticationProcessingFilter - PullRequest
1 голос
/ 12 апреля 2019

Я создал фильтр, и в суперструкторе фильтра он требует defaultFilterProcessesUrl. Я выбрал все запросы по URL /v1/**.

Мне нужно идти не вошли в систему /v1/users (POST метод) и /v1/users/signin (POST метод), но фильтр не позволяет. Как решить эту проблему?

JWT фильтр:

public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationTokenFilter() {
        super("/v1/**");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

         String header = request.getHeader("Authorization");
         if(header == null || !header.startsWith("Bearer")){
             throw new RuntimeException("JWT token is missing");
         }

         String authenticationToken = header.substring(7);

        JwtAuthenticationToken token = new JwtAuthenticationToken(authenticationToken);
        return getAuthenticationManager().authenticate(token);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);
        chain.doFilter(request, response);
    }
}

Конфигурация Spring Security:

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationProvider authenticationProvider;
    @Autowired
    private JwtAuthenticationEntryPoint entryPoint;

    @Bean
    public AuthenticationManager authenticationManager(){
        return new ProviderManager(Collections.singletonList(authenticationProvider));
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter(){
        JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
        return filter;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
                .antMatchers(HttpMethod.POST, "/v1/users")
                .antMatchers(HttpMethod.POST, "/v1/users/signin")
                .antMatchers(HttpMethod.POST, "/token");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
             .csrf().disable()
             .authorizeRequests()
                .anyRequest().hasAnyRole("SG_ADMIN", "O_ADMIN", "OS_ADMIN")
                .and()
             .exceptionHandling().authenticationEntryPoint(entryPoint)
                .and()
             .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        http.headers().cacheControl();
    }
}

1 Ответ

0 голосов
/ 13 апреля 2019

Вы можете использовать другой конструктор с RequestMatcher, см. AbstractAuthenticationProcessingFilter:

AbstractAuthenticationProcessingFilter

protected AbstractAuthenticationProcessingFilter(RequestMatcher requiresAuthenticationRequestMatcher)

Создает новый экземпляр

Параметры:

requiresAuthenticationRequestMatcher - RequestMatcher, используемый для определения необходимости аутентификации. Не может быть нулем.

Ваш модифицированный код:

public JwtAuthenticationTokenFilter() {
    super(customRequestMatcher);
}

с

 RequestMatcher customRequestMatcher = new AndRequestMatcher(
      new AntPathRequestMatcher("/v1/**"), 
      new NegatedRequestMatcher(
          new AntPathRequestMatcher("/v1/users", "POST")
      ),
      new NegatedRequestMatcher(
          new AntPathRequestMatcher("/v1/users/signin", "POST")
      )
 );
...