ubuntu 使用WebSecurityConfiguration,因为不再支持WebSecurityConfigurerAdapter选项,而是停留在循环引用中[重复]

um6iljoc  于 2023-10-17  发布在  其他
关注(0)|答案(1)|浏览(105)

这个问题已经有答案了

Spring Boot circular reference is already handled in application.properties but seems ignored by Java Spring Boot executable jar file(1个答案)
2个月前关闭。
因此我使用Java Sping Boot 创建了这个简单登录系统应用程序,并使用Spring Security进行身份验证。
这是应用程序的规范:

  • Spring工具套件4.18.0.RELEASE
  • Spring安全6
  • 使用Java 17
  • 构建在Linux ubuntu 22.04之上
  • Thymeleaf
  • 默认情况下,application.properties已位于SBTLEmpManSys/src/main/resources中的resource文件夹中
  • 我使用STS(Spring工具套件)提供的Maven构建功能将这些作品打包成可执行的jar文件

当我想为SecurityConfiguration.java使用WebSecurityConfigurerAdapter时,IDE没有提供该选项。它提供了WebSecurityConfiguration,所以我使用它。结果它给出了循环引用。
这是一个图表:

  1. The dependencies of some of the beans in the application context form a cycle:
  2. ┌─────┐
  3. | securityConfiguration (field private org.springframework.security.config.annotation.web.builders.HttpSecurity org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.httpSecurity)
  4. | org.springframework.security.config.annotation.web.configuration.HttpSecurityConfiguration.httpSecurity defined in class path resource [org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]
  5. └─────┘

我通过在application.properties中设置spring.main.allow-circular-reference=true作为临时解决方案来完成我的工作。但是这个问题会在可执行的.jar文件中重新出现
另一方面,我需要这个安全配置文件为我的服务实现文件EmpServiceImpl.java提供BCryptPasswordEncoder
我试着在这里和那里使用@Lazy,但没有效果。我也试着通过谷歌和这个论坛来解决这个问题,但仍然无法解决。
有人能帮忙吗?这真让我给予头疼。
这是我的文件。
这是安全配置

  1. package com.kastamer.sbtl.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.Lazy;
  6. import org.springframework.context.annotation.PropertySource;
  7. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  8. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  9. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  10. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
  11. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  12. import org.springframework.security.web.SecurityFilterChain;
  13. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  14. import com.kastamer.sbtl.service.EmpService;
  15. @Configuration
  16. @PropertySource(value = "classpath:application.properties")
  17. @EnableWebSecurity
  18. public class SecurityConfiguration extends WebSecurityConfiguration {
  19. // public EmpService empService;
  20. // @Lazy --> NO EFFECT
  21. @Bean
  22. public BCryptPasswordEncoder passwordEncoder() {
  23. // TODO Auto-generated method stub
  24. return new BCryptPasswordEncoder();
  25. }
  26. // @Lazy --> NO EFFECT
  27. @Bean
  28. public SecurityFilterChain configure(HttpSecurity http) throws Exception {
  29. // TODO Auto-generated method stub
  30. AuthenticationManagerBuilder authManBuild = http.getSharedObject(AuthenticationManagerBuilder.class);
  31. http.authorizeHttpRequests((requests) -> requests.requestMatchers(
  32. "/registrasi",
  33. "/js**",
  34. "/css**",
  35. "/img**")
  36. .permitAll().anyRequest().authenticated())
  37. .formLogin((form) -> form.loginPage("/login").permitAll())
  38. .logout((logout) -> logout.invalidateHttpSession(true).clearAuthentication(true).logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout").permitAll());
  39. return http.build();
  40. }
  41. }

以下是服务实现:

  1. package com.kastamer.sbtl.service;
  2. import java.util.Arrays;
  3. import java.util.Collection;
  4. import java.util.List;
  5. import java.util.Optional;
  6. import java.util.stream.Collectors;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.annotation.Lazy;
  9. import org.springframework.data.domain.Page;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Pageable;
  12. import org.springframework.data.domain.Sort;
  13. import org.springframework.security.core.GrantedAuthority;
  14. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  15. import org.springframework.security.core.userdetails.UserDetails;
  16. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  17. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  18. import org.springframework.stereotype.Service;
  19. import com.kastamer.sbtl.model.EmpRole;
  20. import com.kastamer.sbtl.model.Employee;
  21. import com.kastamer.sbtl.repository.EmployeeRepository;
  22. import com.kastamer.sbtl.web.dto.EmpRegistrationDTO;
  23. @Service
  24. public class EmpServiceImpl implements EmpService {
  25. @Autowired
  26. private EmployeeRepository empRepDAO;
  27. @Autowired
  28. private BCryptPasswordEncoder passwordEncoder;
  29. //@Autowired //THIS is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NO EFFECT
  30. //public EmpServiceImpl(@Lazy EmployeeRepository empRepDAO) { //ANNOTATION '@Lazy' is ADDITION to AVOID CIRCULAR REFERENCE --> ANNOTATION NO EFFECT
  31. public EmpServiceImpl(EmployeeRepository empRepDAO) {
  32. super();
  33. this.empRepDAO = empRepDAO;
  34. }
  35. @Override
  36. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  37. // TODO Auto-generated method stub
  38. Employee pegawai = empRepDAO.findByEmail(username);
  39. if (pegawai == null) {
  40. throw new UsernameNotFoundException("Email atau kata sandi tidak cocok!");
  41. }
  42. return new org.springframework.security.core.userdetails.User(pegawai.getEmail(), pegawai.getPassword(), mapRolesToAuthority(pegawai.getRoles())); //return null;
  43. }
  44. @Override
  45. public Employee save(EmpRegistrationDTO empRegistrationDTO) {
  46. // TODO Auto-generated method stub
  47. Employee karyawan = new Employee(
  48. empRegistrationDTO.getFullName(),
  49. empRegistrationDTO.getEmail(),
  50. passwordEncoder.encode(empRegistrationDTO.getPassword()),
  51. Arrays.asList(new EmpRole("ROLE_USER")));
  52. return empRepDAO.save(karyawan); //return null;
  53. }
  54. @Override
  55. public void simpanPembaruanData(Employee employee) {
  56. // TODO Auto-generated method stub
  57. employee.setPassword(passwordEncoder.encode(employee.getPassword()));
  58. this.empRepDAO.save(employee);
  59. }
  60. private Collection<? extends GrantedAuthority> mapRolesToAuthority(Collection<EmpRole> roles) {
  61. // TODO Auto-generated method stub
  62. return roles.stream().map(role -> new SimpleGrantedAuthority(role.getNamaRole())).collect(Collectors.toList());
  63. }
  64. //PART POJOK KARYAWAN
  65. @Override
  66. public List<Employee> getAllEmployees() {
  67. // TODO Auto-generated method stub
  68. return empRepDAO.findAll(); //return null;
  69. }
  70. @Override
  71. public Employee getEmployeeById(long id) {
  72. // TODO Auto-generated method stub
  73. Optional<Employee> optEmp = empRepDAO.findById(id);
  74. Employee empl = null;
  75. if (optEmp.isPresent()) {
  76. empl = optEmp.get();
  77. } else {
  78. throw new RuntimeException("Karyawan dengan emp_id '" + id + "' tidak bisa ditemukan");
  79. }
  80. return empl; //return null;
  81. }
  82. @Override
  83. public void deleteEmployeeById(long id) {
  84. // TODO Auto-generated method stub
  85. this.empRepDAO.deleteById(id);
  86. }
  87. @Override
  88. public Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortAscOrDesc) {
  89. // TODO Auto-generated method stub
  90. Sort runut = sortAscOrDesc.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
  91. Pageable pageable = PageRequest.of(pageNo - 1, pageSize, runut);
  92. return this.empRepDAO.findAll(pageable); //return null;
  93. }
  94. }

这是application.properties

  1. # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
  2. spring.datasource.url=jdbc:postgresql://localhost:5432/myDB
  3. spring.datasource.username=[POSTGRES_LOGIN]
  4. spring.datasource.password=[POSTGRES_PASSWORD]
  5. spring.datasource.driver-class-name=org.postgresql.Driver
  6. # The PostgreSQL dialect makes Hibernate generate better Postgresql for the chosen databse
  7. spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
  8. # Hibernate ddl auto (create, create-drop, validate, update, none --> 'default')
  9. spring.jpa.hibernate.ddl-auto=update
  10. # Prepare logging-time system for Spring-Boot engine & will print logs in console (also work as work-level to monitor generated HQL in console)
  11. logging.level.org.hibernate.sql=debug
  12. logging.level.org.hibernate.type=trace
  13. #spring.jpa.show-sql=true
  14. # Default user login and password for spring security web login page (if spring security is enabled)
  15. #spring.security.user.name=spring
  16. #spring.security.user.password=spring123
  17. #spring.security.user.roles=USER
  18. spring.main.allow-bean-definition-overriding=true
  19. #spring.main.allow-circular-references=true
lymnna71

lymnna711#

您可以通过将密码编码器的工厂方法设置为静态来打破这种循环:

  1. @Bean
  2. public static BCryptPasswordEncoder passwordEncoder() {
  3. return new BCryptPasswordEncoder();
  4. }

这样,密码编码器的创建就不再依赖于被示例化的配置类的示例。

相关问题