Используйте setFlterProccessUrl() дважды

#spring-boot #authentication #spring-data-jpa #jwt

#пружинный ботинок #идентификация #весна-данные-jpa #агентство jwt

Вопрос:

у меня есть две конечные точки входа в систему, и я хочу их аутентифицировать. я настроил фильтр, который обрабатывает две конечные точки, но я хочу, чтобы фильтр обрабатывал два маршрута. как я могу это сделать, поскольку метод setFilterProcessUrl обрабатывает только один

вот основной код конфигурации безопасности

 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {   @Qualifier("user")  @Autowired  private UserDetailsService userDetailsService;   @Qualifier("customer")  @Autowired  private UserDetailsService customerDetailsService;   @Autowired  private BCryptPasswordEncoder bCryptPasswordEncoder;   @Override  protected void configure(AuthenticationManagerBuilder auth) throws Exception {  auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);  auth.userDetailsService(customerDetailsService).passwordEncoder(bCryptPasswordEncoder);  }   @Override  protected void configure(HttpSecurity http) throws Exception {  CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean());  customAuthenticationFilter.setFilterProcessesUrl("/customers/login");  customAuthenticationFilter.setFilterProcessesUrl("/users/login");    http.csrf().disable();  http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);  http.authorizeRequests().antMatchers("**/signup").permitAll();  http.authorizeRequests().antMatchers("**/login").permitAll();  //http.authorizeRequests().antMatchers("/users/**").hasAnyAuthority("ROLE_ADMIN");  //http.authorizeRequests().antMatchers("/customers/**").hasAnyAuthority("ROLE_USER");  http.authorizeRequests().antMatchers("/categories/**").hasAnyAuthority("ROLE_USER");  http.authorizeRequests().antMatchers("/products/**").hasAnyAuthority("ROLE_USER");  http.authorizeRequests().antMatchers("/serials/**").hasAnyAuthority("ROLE_USER");  http.authorizeRequests().antMatchers("/orders/**").hasAnyAuthority("ROLE_CUSTOMERS");  http.authorizeRequests().anyRequest().authenticated();  http.addFilter(customAuthenticationFilter);  http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);  }   @Bean  @Override  public AuthenticationManager authenticationManagerBean() throws Exception {  return super.authenticationManagerBean();  } }  

а вот и фильтр

 public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {   @Autowired  private AuthenticationManager authenticationManager;   public CustomAuthenticationFilter(AuthenticationManager authenticationManager) {  this.authenticationManager = authenticationManager;  }   @Override  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {  if(request.getServletPath().equals("/users/login")) {  System.out.print("fat user");  String username = request.getParameter("username");  String password = request.getParameter("password");  UsernamePasswordAuthenticationToken authenticationToken =  new UsernamePasswordAuthenticationToken(username, password);  return authenticationManager.authenticate(authenticationToken);  }  else {  System.out.print("fat customer");  String phoneNumber = request.getParameter("phoneNumber");  String password = request.getParameter("password");  UsernamePasswordAuthenticationToken authenticationToken =  new UsernamePasswordAuthenticationToken(phoneNumber, password);  return authenticationManager.authenticate(authenticationToken);  }  }   @Override  protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {  User user = (User) authentication.getPrincipal();  Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());  String access_token = JWT.create()  .withSubject(user.getUsername())  .withExpiresAt(new Date(System.currentTimeMillis()   3600 * 60 * 1000))  .withIssuer(request.getRequestURL().toString())  .withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))  .sign(algorithm);  String refresh_token = JWT.create()  .withSubject(user.getUsername())  .withExpiresAt(new Date(System.currentTimeMillis()   366 * 24 * 60 * 60 * 1000))  .withIssuer(request.getRequestURL().toString())  .sign(algorithm); // response.setHeader("access_token", access_token); // response.setHeader("refresh_token", refresh_token);  Maplt;String, Stringgt; tokens = new HashMaplt;gt;();  tokens.put("access_token", access_token);  tokens.put("refresh_token", refresh_token);  response.setContentType(APPLICATION_JSON_VALUE);  new ObjectMapper().writeValue(response.getOutputStream(), tokens);  } }  

как я могу это сделать без создания нового фильтра ??