[英]Spring Security circular bean dependency
我目前正在开发 Vaadin spring 应用程序。 根据应用规范,用户的认证/授权必须通过jdbcTemplate
查询数据库来完成。 如何解决这个问题? 我正在使用 Spring Boot 1.4.2.RELEASE。
更新:此方法适用于 Spring Boot 1.1.x.RELEASE,但在其最新版本上会产生以下错误消息。
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| jdbcAccountRepository defined in file [repositories\JdbcAccountRepository.class]
↑ ↓
| securityConfiguration.WebSecurityConfig (field services.JdbcUserDetailsServicessecurity.SecurityConfiguration$WebSecurityConfig.userDetailsService)
↑ ↓
| jdbcUserDetailsServices (field repositories.JdbcAccountRepository services.JdbcUserDetailsServices.repository)
└─────┘
原始代码如下所示:
账户资料库:
public interface AccountRepository {
void createAccount(Account user) throws UsernameAlreadyInUseException;
Account findAccountByUsername(String username);
}
JdbcAccountRepository:
@Repository
public class JdbcAccountRepository implements AccountRepository {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
private final JdbcTemplate jdbcTemplate;
private final PasswordEncoder passwordEncoder;
@Autowired
public JdbcAccountRepository(JdbcTemplate jdbcTemplate, PasswordEncoder passwordEncoder) {
this.jdbcTemplate = jdbcTemplate;
this.passwordEncoder = passwordEncoder;
}
@Transactional
@Override
public void createAccount(Account user) throws UsernameAlreadyInUseException {
try {
jdbcTemplate.update(
"insert into Account (firstName, lastName, username, password, role) values (?, ?, ?, ?, ?)",
user.getFirstName(),
user.getLastName(),
user.getUsername(),
passwordEncoder.encode(
user.getPassword()),
user.getRole()
);
} catch (DuplicateKeyException e) {
throw new UsernameAlreadyInUseException(user.getUsername());
}
}
@Override
public Account findAccountByUsername(String username) {
return jdbcTemplate.queryForObject(
"select username, password, firstName, lastName, role from Account where username = ?",
(rs, rowNum) -> new Account(
rs.getString("username"),
rs.getString("password"),
rs.getString("firstName"),
rs.getString("lastName"),
rs.getString("role")),
username
);
}
}
JdbcUserDetails 服务:
@Service
public class JdbcUserDetailsServices implements UserDetailsService {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Autowired
JdbcAccountRepository repository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
Account account = repository.findAccountByUsername(username);
User user = new User(
account.getUsername(),
account.getPassword(),
AuthorityUtils.createAuthorityList(
account.getRole()
)
);
return user;
} catch (DataAccessException e) {
LOGGER.debug("Account not found", e);
throw new UsernameNotFoundException("Username not found.");
}
}
}
安全配置:
@Configuration
@ComponentScan
public class SecurityConfiguration {
@Autowired
ApplicationContext context;
@Autowired
VaadinSecurity security;
@Bean
public PreAuthorizeSpringViewProviderAccessDelegate preAuthorizeSpringViewProviderAccessDelegate() {
return new PreAuthorizeSpringViewProviderAccessDelegate(security, context);
}
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public static class GlobalMethodSecurity extends GlobalMethodSecurityConfiguration {
@Bean
@Override
protected AccessDecisionManager accessDecisionManager() {
return super.accessDecisionManager();
}
}
@Configuration
@EnableWebSecurity
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JdbcUserDetailsServices userDetailsService;
@Autowired
DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
/*
* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
* #configure(org.springframework.security.config.annotation.web.builders.WebSecurity)
*/
@Override
public void configure(WebSecurity web) throws Exception {
//Ignoring static resources
web.ignoring().antMatchers("/VAADIN/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean(name="authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/*
* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
* #configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.and()
.csrf().disable();
}
}
}
PS如果将Spring Boot版本降级到[1.1.5,1.2.0],就不会出现这个问题(由于其他依赖,我必须使用最新的)
您可以使用基于setter 的依赖注入替换基于构造函数的依赖注入来解决循环,请参阅Spring Framework 参考文档:
循环依赖
如果您主要使用构造函数注入,则可能会创建无法解决的循环依赖场景。
例如:A类通过构造函数注入需要B类的实例,B类通过构造函数注入需要A类的实例。 如果您将类 A 和 B 的 bean 配置为相互注入,则 Spring IoC 容器在运行时检测到此循环引用,并抛出
BeanCurrentlyInCreationException
。一种可能的解决方案是编辑一些类的源代码,以便由 setter 而不是构造函数来配置。 或者,避免构造函数注入并仅使用 setter 注入。 也就是说,虽然不推荐,但是可以通过setter注入来配置循环依赖。
与典型情况(没有循环依赖)不同,bean A 和 bean B 之间的循环依赖强制其中一个 bean 在完全初始化之前注入另一个 bean(经典的鸡/蛋场景)。
我更喜欢@Lazy
方法。 这样我就可以坚持一种模式。
你PasswordEncoder
bean定义是WebSecurityConfig
这就需要JdbcUserDetailsServices
。 JdbcUserDetailsServices
再次依赖于需要PasswordEncoder
JdbcAccountRepository
。 于是循环就形成了。 一个简单的解决方案是从WebSecurityConfig
取出PasswordEncoder
bean 定义。 即使在SecurityConfiguration
类中也能解决循环问题。
我在一个类的构造函数中使用了@Lazy
,它解决了我的问题:
public class AService {
private BService b;
public ApplicantService(@NonNull @Lazy BService b) {
this.b = b;
}
}
public class BService {
private AService a;
public ApplicantService(@NonNull BService a) {
this.a = a;
}
}
@Zeeshan Adnan 是对的。 采取PasswordEncoder
出WebSecurityConfig
解决循环依赖问题。
来自 Zeeshan 的回答:
您的 PasswordEncoder bean 定义在需要 JdbcUserDetailsServices 的 WebSecurityConfig 中。 JdbcUserDetailsServices 再次依赖于需要 PasswordEncoder 的 JdbcAccountRepository。 于是循环就形成了。 一个简单的解决方案是从 WebSecurityConfig 中取出 PasswordEncoder bean 定义。 即使在 SecurityConfiguration 类中也能解决循环问题。
另一个简单的建议是将 PasswordEncoder 定义仅从 public 更改为 public static:
@Bean(name = "passwordEncoder")
public PasswordEncoder passwordencoder() {
return new CustomPasswordEncoder();
}
到:
@Bean(name = "passwordEncoder")
public static PasswordEncoder passwordencoder() {
return new CustomPasswordEncoder();
}
我为 PasswordEncoder 创建了一个单独的配置 class,然后将其导入到 securityconfig class 中,它解决了我的问题。 SourceCode here with spring boot latest -> https://github.com/juyelhushen/JWT-springboot-3-Latest.git
解决方案之一是不使用构造函数。 例如,而不是:
private final JdbcTemplate jdbcTemplate;
private final PasswordEncoder passwordEncoder;
@Autowired
public JdbcAccountRepository(JdbcTemplate jdbcTemplate, PasswordEncoder passwordEncoder) {
this.jdbcTemplate = jdbcTemplate;
this.passwordEncoder = passwordEncoder;
}
您可以使用:
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private PasswordEncoder passwordEncoder;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.