开发一个Spring启动应用程序,该应用程序实现基于Spring boot security基本身份验实现了UserDetailsService并覆盖了loadUserByUsername方法 . 单步执行该方法,我发现从我的数据库用户表中成功检索了用户名,密码和角色信息 .
我的UserDetailsService loadUserByUsername代码是
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName);
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole());
User(activeUserInfo.getUserName(),
activeUserInfo.getPassword(), Arrays.asList(authority));
return userDetails;
}
退回DaoAUthenticationProvider retrieveUser包含从用户表查找返回的值,但AbstractUserDetailsAuthenticationProvider身份验证方法显示权限为零长度数组,正确返回用户名和密码 . 没有权限值导致返回401错误凭据错误 .
我正在和邮递员一起测试 . 使用以下定义的用户表使用MySql 5.7.11:
CREATE TABLE IF NOT EXISTS `users` (
`username` varchar(50) NOT NULL,
`password` varchar(100) NOT NULL,
`full_name` varchar(100) NOT NULL,
`role` varchar(50) NOT NULL,
`country` varchar(100) NOT NULL,
`enabled` tinyint(1) NOT NULL,
PRIMARY KEY (`username`)
);
密码使用BCryptPasswordEncoder存储,并通过postman以纯文本形式发送密码 .
我的application.properties定义为:
spring.datasource.url=jdbc:mysql://localhost:3306/actotracker?useSSL=false
spring.datasource.username=root
spring.datasource.password=Dial0gicRots
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
security.basic.enabled=true
security.basic.realm=Spring
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
尝试手动将权限值设置为“ROLE_ADMIN”而不影响结果 . 关于我做错了什么的指针?
Java版本1.8 Spring启动1.5.3.RELEASE
我注册密码编码器的代码:
private final Logger log = LoggerFactory.getLogger(MyApplication.class);
@Autowired
private AppUserDetailService appUserDetailsService;
@Autowired
private AppAuthenticationEntryPoint appAuthenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
log.info("In configure");
http.csrf().disable()
.authorizeRequests()
.antMatchers("/user/**").hasAnyRole("ROLE_ADMIN","ROLE_USER")
.and().httpBasic().realmName("Spring")
// .and().httpBasic()
.authenticationEntryPoint(appAuthenticationEntryPoint);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
log.info("configGlobal");
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
auth.userDetailsService(appUserDetailsService).passwordEncoder(passwordEncoder);
}
邮递员值:http://localhost:8080/user/distances用户名字段:tim密码:纯文本密码值验证设置为基本验证
1 回答
dur是正确的,401是由密码不匹配引起的 . 我编写了一个小例程来获取纯文本字符串并将其加密 . `
我在用户身份验证表中使用/存储了encPassword值 .
步入BCryptPasswordEncoder类BCrypt.checkpw,我发现我的原始文本字符串被转换为不同的加密值 . 使用新的加密值更新了我的数据库用户表条目,我的授权成功 .