Не вызывается метод RestController в Spring Boot с кастомным фильтром
Пытаюсь сделать приложение с кастомной аутенфикацией, почему-то не вызывается метод контроллера. Контроллер вызывается с фронта, проходит через мой фильтр, в браузере приходит ответ Ок, но сам контроллер почему-то не вызывается. В чём моя ошибка?
const saveUserData = async (userInfo) => {
return await axiosInstance.post('saveUser', userInfo);
}
Контроллер
@RestController
@CrossOrigin
public class AuthController {
final UserService userService;
public AuthController(UserService userService) {
this.userService = userService;
}
@PostMapping(value = "/saveUser")
@ResponseBody
public VkUser saveUserInfo(@RequestBody VkUser vkUSer) {
return vkUSer;
}
}
Кастомный фильтр @Component public class VkMiniAppAuthenticationFilter extends OncePerRequestFilter {
private final VkMiniappUserDetailService userDetailService;
final SignChecker signChecker;
private final AuthenticationEntryPoint authenticationEntryPoint;
public VkMiniAppAuthenticationFilter(VkMiniappUserDetailService userDetailService,
SignChecker signChecker,
AuthenticationEntryPoint authenticationEntryPoint) {
this.userDetailService = userDetailService;
this.signChecker = signChecker;
this.authenticationEntryPoint = authenticationEntryPoint;
}
private final List<String> excludePatches = new ArrayList<>();
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
excludePatches.add("/saveUser");
if(excludePatches.stream().anyMatch(p -> antPathMatcher.match(p, request.getServletPath()))) {
chain.doFilter(request, response);
return;
}
String sign = request.getHeader("authorization");
if (sign == null || sign.isEmpty()) {
chain.doFilter(request, response);
return;
}
try {
if (signChecker.check(request)) {
String vkId = request.getHeader("vk_user_id");
if (vkId == null || vkId.isEmpty()) {
throw new AuthenticationCredentialsNotFoundException("Не указан VK ID");
}
UserDetails userDetails = userDetailService.loadUserByUsername(vkId);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
chain.doFilter(request, response);
}else throw new BadCredentialsException("Токен не прошёл валидацию");
} catch (AuthenticationException e) {
SecurityContextHolder.clearContext();
this.authenticationEntryPoint.commence(request, response, e);
return;
} catch (Exception e) {
e.printStackTrace();
}
chain.doFilter(request, response);
}
}
Конфиг SpringSecurity @Configuration public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
final VkMiniappUserDetailService userDetailService;
final VkMiniAppAuthenticationFilter vkMiniAppAuthenticationFilter;
final VkMiniAppAuthenticationEntryPoint entryPoint;
public SpringSecurityConfig(VkMiniappUserDetailService userDetailService, VkMiniAppAuthenticationFilter vkMiniAppAuthenticationFilter, VkMiniAppAuthenticationEntryPoint entryPoint) {
this.userDetailService = userDetailService;
this.vkMiniAppAuthenticationFilter = vkMiniAppAuthenticationFilter;
this.entryPoint = entryPoint;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOriginPatterns(Collections.singletonList("*"));
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
http.cors().and().csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and()
.addFilterBefore(vkMiniAppAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new CorsFilter(source), VkMiniAppAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(entryPoint)
.and().sessionManagement().disable();
}
}
Ответы (1 шт):
Автор решения: Инга Куксова
→ Ссылка
Я добавила .antMatchers("/saveUser").permitAll(), и всё заработало.

