我在SO中进行了大量搜索,发现各种情况下Authentication为null,但都不是我的情况。我认为我已经做了所有事情,但不知道为什么getAuthentication()
返回null。这是我所做的:
SecurityConfiguration类:
@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类:
@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
之类的方法,但是都返回null。
我想知道为什么Authentication
类中的SecurityConfiguration
仍然为null时,我必须对所有请求进行身份验证。
为什么会这样?