目标:使用默认安全配置向 Spring Boot 添加 jdbc 身份验证。
来源可以找到here
configure the global AuthenticationManager by autowiring an AuthenticationManagerBuilder into a method in one of your @Configuration classes
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
鉴于上述内容,添加以下内容 ( found here ):
@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class AuthenticationManagerConfig {
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("ROLE_USER").and()
.withUser("admin").password("password").roles("ROLE_USER", "ROLE_ADMIN");
}
}
产生错误:
java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer@13404f75 to already built object
在日志中,我们可以看到自动配置在不应该做的事情时做了它的事情:
2016-02-02 22:52:48.047 DEBUG 30487 --- [ost-startStop-1] eGlobalAuthenticationAutowiredConfigurer : Eagerly initializing {org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration=org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$$EnhancerBySpringCGLIB$$627430a8@78acaa86}
2016-02-02 22:52:48.074 DEBUG 30487 --- [ost-startStop-1] .s.BootGlobalAuthenticationConfiguration : Eagerly initializing {user=com.msyla.usergreeter.user.User$$EnhancerBySpringCGLIB$$3cd414fd@73128671, coreConfig=com.msyla.usergreeter.user.core.config.CoreConfig$$EnhancerBySpringCGLIB$$30c07250@6ed3c66b}
2016-02-02 22:52:48.095 INFO 30487 --- [ost-startStop-1] b.a.s.AuthenticationManagerConfiguration :
Using default security password: 5b33158f-156d-43f4-892f-6c452f15e1cc
问题:这里所要求的只是拥有默认的启动配置,除了用户的存储位置(jdbc 而不是内存)。我做错了吗?文档有错吗?我尝试了其他几条路线,但均无济于事。
提前致谢!
最佳答案
经过大量工作后,我想起了如何正确使用 Spring,即单步执行他们的代码,以便更好地理解如何通过外科手术解决我的需求。经过一些调查,确定了需要修改/扩展的类。结果是:
@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class AuthenticationManagerConfig extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
}
以上内容将指示 spring 通过 jdbc 进行查找,同时保持其他所有内容自动配置。
关于java - 在 Spring Boot 中配置 JDBC 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35164589/