После аутентификации пользователя в Spring при повторном запросе не удается получить доступ к пользователю в SecurityContextHolder
Потребовалось реализовать простой Api сервис на Spring. Использую 6 версию Spring Security.
Для аутентификации использую стандартный UsernamePasswordAuthenticationToken. Требуется, чтобы при повторном обращении можно было получить авторизованного пользователя, для ручной проверки доступа к определенным данным. Первоначально отправляю запрос на вход в систему. Код контроллера:
@PostMapping("/signin")
public ResponseEntity<String> authenticateUser(@RequestBody LoginDTO loginDto){
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
loginDto.getUsername(), loginDto.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed-in successfully!", HttpStatus.OK);
}
Для теста создал еще один контроллер, возвращающий имя пользователя. На этом этапе возникает проблема, через debug проверил что на этапе входа в систему authentication действительно возвращает моего пользователя, но при обращении по второму url пользователь становится "anonymousUser". Код тестового контроллера:
@GetMapping(value = "/test")
public ResponseEntity<String> test() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return new ResponseEntity<>("Hello " + auth.getName(), HttpStatus.OK);
}
Код настройки Spring security:
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
private UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService){
this.userDetailsService = userDetailsService;
}
@Bean
public static PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests(authorize ->
authorize.requestMatchers("/auth/**", "/test/**").permitAll()
.anyRequest().authenticated());
return http.build();
}
}