【发布时间】:2017-04-20 05:24:26
【问题描述】:
我正在通过 ApplicationRunner 使用基于 Spring Security / JPA 的身份验证将管理员/测试用户添加到我的 Spring Boot 应用程序中。
在此之前我有一个data.sql文件,但是我需要支持多个数据库,所以我在寻找一个可移植的解决方案。
我有一个供用户使用的 Spring Data JPA 存储库,并且像这样简单地添加了我的用户:
@Component
public class MyRunner implements ApplicationRunner {
private UserRepository userRepository;
@Autowired
public MyRunner(UserRepository userRepository) {
this.userRepository = userRepository;
}
/* (non-Javadoc)
* @see org.springframework.boot.ApplicationRunner#run(org.springframework.boot.ApplicationArguments)
*/
@Override
public void run(ApplicationArguments args) throws Exception {
User admin = new User("admin", "admin", Roles.ROLE_ADMIN);
userRepository.saveAndFlush(admin);
}
}
效果很好。但我激活了 Spring 全局方法安全性,以保护同样通过 REST 公开的 UserRepository:
@PreAuthorize("hasRole('ROLE_ADMIN')")
@Override
<S extends User> S save(S user);
但是后来添加用户失败了,因为我没有被授权。我试过这个黑客:
@Override
public void run(ApplicationArguments args) throws Exception {
User admin = new User("admin", "admin", Roles.ROLE_ADMIN);
Authentication auth = new UsernamePasswordAuthenticationToken(admin, null,
AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
SecurityContextHolder.getContext().setAuthentication(auth);
userRepository.saveAndFlush(admin);
SecurityContextHolder.clearContext();
}
添加了用户,但网络应用本身的身份验证现在已彻底破坏...
我只得到 AuthenticationCredentialsNotFoundException
o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=Mon Dec 05 19:12:10 CET 2016, principal=<unknown>, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException, message=An Authentication object was not found in the SecurityContext}]
【问题讨论】:
标签: java spring spring-security spring-boot spring-data-jpa