java—从spring上的当前会话获取用户信息?

qjp7pelc  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(502)

我一直在尝试从当前会话获取用户信息,以执行一些类似findbyusername的操作。我尝试过@authenticationprinciple,但即使我将userdetails实现提供给它,它也只返回null。我也尝试过securitycontextholder方法,它返回匿名用户(?)。无论哪种方式都没有达到预期的效果。尝试了所有的解决方案,我可以在互联网上找到迄今为止,但没有运气。控制器;

  1. @Controller
  2. public class Home {
  3. EntryService entryService;
  4. public Home(EntryService entryService) {
  5. this.entryService = entryService;
  6. }
  7. @GetMapping("/Home")
  8. public String registration(Entry entry, Model model) {
  9. //See what it returns
  10. System.out.println(getUsername());
  11. List<Entry> entries = new ArrayList<>(entryService.getAllEntries());
  12. model.addAttribute("entryList", entries);
  13. model.addAttribute("entry", entry);
  14. return "/home";
  15. }
  16. public String getUsername() {
  17. SecurityContext context = SecurityContextHolder.getContext();
  18. Authentication authentication = context.getAuthentication();
  19. if (authentication == null)
  20. return null;
  21. Object principal = authentication.getPrincipal();
  22. if (principal instanceof UserDetails) {
  23. return ((UserDetails) principal).getUsername();
  24. } else {
  25. return principal.toString();
  26. }
  27. }
  28. }

安全;

  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Bean
  4. public PasswordEncoder passwordEncoder() {
  5. return new BCryptPasswordEncoder();
  6. }
  7. @Autowired
  8. public DetailsService detailsService() {
  9. return new DetailsService();
  10. }
  11. protected void configure(HttpSecurity http) throws Exception {
  12. http.
  13. authorizeRequests().
  14. antMatchers("/register").
  15. permitAll().
  16. antMatchers("/home").
  17. hasRole("USER").
  18. and().
  19. csrf().
  20. disable().
  21. formLogin().
  22. loginPage("/").
  23. permitAll().
  24. passwordParameter("password").
  25. usernameParameter("username").
  26. defaultSuccessUrl("/home").
  27. failureUrl("/error").
  28. and().
  29. logout().
  30. logoutUrl("/logout");
  31. }
  32. @Override
  33. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  34. auth.userDetailsService(detailsService()).passwordEncoder(passwordEncoder());
  35. }
  36. }

用户详细信息;

  1. public class UserDetail implements UserDetails {
  2. private final String username;
  3. private final String password;
  4. private final boolean active;
  5. private final List<GrantedAuthority> roles;
  6. public UserDetail(User user) {
  7. this.username = user.getUserName();
  8. this.password = user.getPassword();
  9. this.active = user.getActive();
  10. this.roles = Arrays.stream(user.getRole().toString().split(",")).
  11. map(SimpleGrantedAuthority::new).
  12. collect(Collectors.toList());
  13. }
  14. @Override
  15. public Collection<? extends GrantedAuthority> getAuthorities() {
  16. return roles;
  17. }
  18. @Override
  19. public String getPassword() {
  20. return password;
  21. }
  22. @Override
  23. public String getUsername() {
  24. return username;
  25. }
  26. @Override
  27. public boolean isAccountNonExpired() {
  28. return true;
  29. }
  30. @Override
  31. public boolean isAccountNonLocked() {
  32. return true;
  33. }
  34. @Override
  35. public boolean isCredentialsNonExpired() {
  36. return true;
  37. }
  38. @Override
  39. public boolean isEnabled() {
  40. return active;
  41. }
  42. }

用户详细信息服务;

  1. @Service
  2. public class DetailsService implements UserDetailsService {
  3. @Autowired
  4. UserRepository userRepository;
  5. @Override
  6. public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
  7. Optional<User> user = userRepository.findByUserName(s);
  8. user.orElseThrow(() -> new UsernameNotFoundException("User not found"));
  9. return user.map(UserDetail::new).get();
  10. }
  11. }

使用基于jpa的身份验证btw,它可以根据需要工作。

pxyaymoc

pxyaymoc1#

在安全上下文中获得匿名用户的唯一原因是您没有经过身份验证。尝试添加 .anyRequest().authenticated() 刚好在…之后 hasRole("USER"). 然后你应该在 SecurityContextHolder.getContext().getAuthentication() . 这将继续使用您指定为的方法 permitAll() .
另外,只是一个观察,但是你的配置中的url匹配器是打开的 /home 并且您的控制器指定 /Home .

相关问题