Rest API Spring. Код 403 при авторизации
Столкнулся с трудностью при настройке авторизации в Spring. Создал два Rest-контроллера: для авторизации и загрузки/скачивания изображений. Делаю запросы к API через Postman, авторизация происходит, однако при попытке взаимодействовать с контроллером изображений всегда получаю код 403. Пробовал вешать disable() на csrf и cors - не помогает.
Буду благодарен любой помощи!
Настроил конфигурацию безопасности следующим образом:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
UserDetailsService userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.
authorizeHttpRequests().
requestMatchers("/api/auth/**").permitAll().
requestMatchers("/api/image/**").authenticated().
and().
csrf().disable().
build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
Контроллер авторизации:
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private RoleRepository roleRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/sign-up")
public ResponseEntity<?> registerUser(@RequestBody AuthDTO authDTO){
if(userService.checkByUsername(authDTO.getUsername()))
return ResponseEntity.badRequest().build();
User user = new User();
user.setUsername(authDTO.getUsername());
user.setPassword(passwordEncoder.encode(authDTO.getPassword()));
Role role = roleRepository.findByRoleName(RoleName.ROLE_USER).get();
user.setRoles(Collections.singleton(role));
userService.addUser(user);
return ResponseEntity.ok().build();
}
@PostMapping("/sign-in")
public ResponseEntity<?> authenticateUser(@RequestBody AuthDTO authDTO){
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authDTO.getUsername(),authDTO.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
User user = userService.getByUsername(authentication.getName());
return ResponseEntity.ok().body(user.getId());
}
}
Контроллер изображений:
@RestController
@RequestMapping("/api/image")
public class ImageController {
@Autowired
private ImageService imageService;
@PostMapping("/upload")
public ResponseEntity<Long> uploadImage(@RequestParam("image")MultipartFile imageFile){
try{
return ResponseEntity.ok().body(imageService.saveImage(imageFile));
}catch (Exception e){
return ResponseEntity.noContent().build();
}
}
@GetMapping(value = "/download/{id}",
produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] downloadImage(@PathVariable Long id){
return imageService.getImageById(id);
}
}
Попытка получить изображение:

