将SpringSecurityConfig迁移到Sping Boot 3 [已关闭]

ppcbkaq5  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(166)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
27天前关闭。
Improve this question
我一直在努力将SecurityConfig文件Map到较新的Spring版本。具体来说,这个问题(我认为)是由UserDetailsService()或与之相关的东西引起的。我试图通过将原始密码传递到登录页面来登录,而加密密码则硬编码到数据库中(我刚刚粘贴了encode()方法返回的字符串)。在尝试这样做的同时,我得到了以下消息:

  1. Hibernate: select u1_0.id,u1_0.name,u1_0.password,u1_0.username from users u1_0 where u1_0.username=?
  2. Hibernate: select a1_0.user_id,a1_0.id,a1_0.authority from authority a1_0 where a1_0.user_id=?

字符串
看起来好像id在某个地方没有正确传递,但我不确定对此有什么感觉。我只是无法正确登录。
下面我将向你展示我来自哪里,我有什么atm,以及其他一些文件,但是它们应该很好,因为在Sping Boot 3中对它们的编码方式没有太多更改。无论如何,因为我不确定它们可能会有帮助,所以它们在这里:
旧文件:

  1. @Configuration
  2. public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  3. @Autowired
  4. private UserDetailsService userDetailsService;
  5. @Bean
  6. public PasswordEncoder getPasswordEncoder() {
  7. return new BCryptPasswordEncoder();
  8. }
  9. @Override
  10. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  11. auth
  12. .userDetailsService(userDetailsService)
  13. .passwordEncoder(getPasswordEncoder());
  14. // auth.inMemoryAuthentication()
  15. // .passwordEncoder(getPasswordEncoder())
  16. // .withUser("[email protected]")
  17. // .password(getPasswordEncoder().encode("asdfasdf"))
  18. // .roles("USER");
  19. }
  20. @Override
  21. protected void configure(HttpSecurity http) throws Exception {
  22. http
  23. .authorizeRequests()
  24. .antMatchers("/").permitAll()
  25. .anyRequest().hasRole("USER").and()
  26. .formLogin()
  27. .loginPage("/login")
  28. .defaultSuccessUrl("/dashboard")
  29. .permitAll()
  30. .and()
  31. .logout()
  32. .logoutUrl("/logout")
  33. .permitAll();
  34. }
  35. }


新文件:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class WebSecurityConfig
  4. {
  5. @Autowired
  6. private UserDetailsService userDetailsService;
  7. @Bean
  8. public UserDetailsService userDetailsService()
  9. {
  10. return new UserDetailsServiceImpl();
  11. }
  12. @Bean
  13. public PasswordEncoder passwordEncoder()
  14. {
  15. return new BCryptPasswordEncoder();
  16. }
  17. @Bean
  18. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception
  19. {
  20. return
  21. http.authorizeHttpRequests()
  22. .requestMatchers("/").permitAll()
  23. .anyRequest().hasRole("USER")
  24. .and()
  25. .formLogin()
  26. .loginPage("/login")
  27. .defaultSuccessUrl("/dashboard")
  28. .permitAll()
  29. .and()
  30. .logout()
  31. .logoutUrl("/logout").permitAll()
  32. .and().build();
  33. }
  34. @Bean
  35. public AuthenticationProvider authenticationProvider()
  36. {
  37. DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
  38. authenticationProvider.setUserDetailsService(userDetailsService());
  39. authenticationProvider.setPasswordEncoder(passwordEncoder());
  40. return authenticationProvider;
  41. }
  42. }


UserDetailsServiceImpl:

  1. @Service
  2. public class UserDetailsServiceImpl implements UserDetailsService
  3. {
  4. @Autowired
  5. private UserRepository userRepo;
  6. @Override
  7. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
  8. {
  9. User user = userRepo.findByUsername(username);
  10. if(user == null)
  11. {
  12. throw new UsernameNotFoundException("Invalid username and password");
  13. }
  14. return new CustomSecurityUser(user);
  15. }
  16. }


CustomSecurityUser:

  1. public class CustomSecurityUser extends User implements UserDetails
  2. {
  3. private static final long serialVersionUID = 464958176L;
  4. public CustomSecurityUser()
  5. {}
  6. public CustomSecurityUser(User user)
  7. {
  8. this.setAuthorities(user.getAuthorities());
  9. this.setId(user.getId());
  10. this.setName(user.getName());
  11. this.setPassword(user.getPassword());
  12. this.setUsername(user.getUsername());
  13. }
  14. @Override
  15. public Set<Authority> getAuthorities()
  16. {
  17. return super.getAuthorities();
  18. }
  19. @Override
  20. public String getPassword()
  21. {
  22. return super.getPassword();
  23. }
  24. @Override
  25. public String getUsername()
  26. {
  27. return super.getUsername();
  28. }
  29. @Override
  30. public boolean isAccountNonExpired()
  31. {
  32. return true;
  33. }
  34. @Override
  35. public boolean isAccountNonLocked()
  36. {
  37. return true;
  38. }
  39. @Override
  40. public boolean isCredentialsNonExpired()
  41. {
  42. return true;
  43. }
  44. @Override
  45. public boolean isEnabled()
  46. {
  47. return true;
  48. }
  49. }


UserRepository:

  1. public interface UserRepository extends JpaRepository<User, Long>
  2. {
  3. User findByUsername(String username);
  4. }


权限:

  1. package com.freshvotes.security;
  2. import org.springframework.security.core.GrantedAuthority;
  3. import com.freshvotes.domain.User;
  4. import jakarta.persistence.Entity;
  5. import jakarta.persistence.GeneratedValue;
  6. import jakarta.persistence.GenerationType;
  7. import jakarta.persistence.Id;
  8. import jakarta.persistence.ManyToOne;
  9. @Entity
  10. public class Authority implements GrantedAuthority
  11. {
  12. private static final long serialVersionUID = -6420181486L;
  13. private Long id;
  14. private String authority;
  15. private User user;
  16. @Override
  17. public String getAuthority()
  18. {
  19. return this.authority;
  20. }
  21. public void setAuthority(String authority)
  22. {
  23. this.authority = authority;
  24. }
  25. @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  26. public Long getId()
  27. {
  28. return this.id;
  29. }
  30. public void setId(Long id)
  31. {
  32. this.id = id;
  33. }
  34. @ManyToOne()
  35. public User getUser()
  36. {
  37. return this.user;
  38. }
  39. public void setUser(User user)
  40. {
  41. this.user = user;
  42. }
  43. }


用户实体:

  1. @Entity
  2. @Table(name = "users")
  3. public class User
  4. {
  5. private Long id;
  6. private String username;
  7. private String password;
  8. private String name;
  9. private Set<Authority> authorities = new HashSet<>();
  10. @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  11. public Long getId()
  12. {
  13. return id;
  14. }
  15. public void setId(Long id)
  16. {
  17. this.id = id;
  18. }
  19. public String getUsername()
  20. {
  21. return username;
  22. }
  23. public void setUsername(String username)
  24. {
  25. this.username = username;
  26. }
  27. public String getPassword()
  28. {
  29. return password;
  30. }
  31. public void setPassword(String password)
  32. {
  33. this.password = password;
  34. }
  35. public String getName()
  36. {
  37. return name;
  38. }
  39. public void setName(String name)
  40. {
  41. this.name = name;
  42. }
  43. @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="user")
  44. public Set<Authority> getAuthorities()
  45. {
  46. return this.authorities;
  47. }
  48. public void setAuthorities(Set<Authority> authorities)
  49. {
  50. this.authorities = authorities;
  51. }
  52. }


我希望这将是有可能作出的东西了。我删除了进口,因为我不能张贴我的问题,否则。

xeufq47z

xeufq47z1#

您的数据库中的数据似乎有问题。我克隆了您的存储库并通过添加数据进行了测试,它似乎在我这边正常运行。
要进行故障排除,请尝试在登录页面上使用以下凭据:密码-user和密码-password
此外,以下是我插入数据库的数据的详细信息:

用户表:

  1. INSERT INTO users(id, name, password, username) values (1, 'kc', '$2a$10$C6454pQIMqMNW76.M8NjYOzvniTgqdl8unnjnWNnMXmkGqE1M9CSC', 'user');

字符串

权限表:

  1. INSERT INTO authority(id, authority, user_id) VALUES (1, 'ROLE_USER', 1);


如果你是新手,我建议在你的application properties文件中添加以下行。这将为Spring Security启用详细的日志记录,帮助你跟踪和调试潜在的问题:
将以下行添加到application.properties文件中:

  1. logging.level.org.springframework.security=TRACE


此外,在WebSecurityConfig中,您可以通过在@EnableWebSecurity annotation中添加debug = true来启用调试。下面是一个示例:

  1. @EnableWebSecurity(debug = true)
  2. public class WebSecurityConfig {
  3. // Your security configuration code here
  4. }

展开查看全部

相关问题