Spring Security程序授权

时间:2016-12-05 18:13:39

标签: java spring spring-security spring-boot spring-data-jpa

我正在通过ApplicationRunner将管理员/测试用户添加到我的Spring Boot应用程序中,并使用基于Spring Security / JPA的身份验证。

在此之前,我有一个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全局方法安全性,以保护UserRepository,这也是通过REST公开的:

@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}]

1 个答案:

答案 0 :(得分:0)

我只是在使用解决方法:

我已停用Method Security,我只是将所有Spring Data Endpoints放在/ data / -prefixed路径后面。然后我可以使用Spring Security和所有不同的修改HTTP方法(POST,PUT,PATCH,DELETE)。