Я много искал в SO и видел различные сценарии, где аутентификация нулевая, но ни один из них не был моим случаем. я думаю, что сделал все, но не знаю, почему getAuthentication()
возвращает ноль. вот что я сделал:
Класс конфигурации безопасности:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests().anyRequest().authenticated().and().formLogin().permitAll();
}
@Autowired
public void configureJpaBasedUsers(AuthenticationManagerBuilder auth,SpringDataUserDetailsService service) throws Exception{
auth.userDetailsService(service);
}
}
SpringDataUserDetailsService class:
@Component
public class SpringDataUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Autowired
public SpringDataUserDetailsService(UserRepository userRepository){
this.userRepository=userRepository;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user=userRepository.findByUsername(s);
return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
Stream.of(user.getRoles()).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
}
}
и вот где происходит ошибка, в imageService:
public void createImaeg(MultipartFile file) throws IOException {
if (!file.isEmpty()) {
Files.copy(file.getInputStream(), Paths.get(Upload_Root, file.getOriginalFilename()));
imageRepository.save(new Image(file.getOriginalFilename(),
userRepository.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName())));
}
}
выдает исключение нулевого указателя, потому что SecurityContextHolder.getContext().getAuthentication().getName()
возвращает ноль. я пробовал разные способы, такие как Principle.getName()
и HttpServletRequest
, но все вернуло ноль.
Мне интересно, почему Authentication
по-прежнему равен нулю, а в классе SecurityConfiguration
я указал, что все запросы должны быть аутентифицированы.
почему это происходит?