【问题标题】:Spring Security Programmatic authorizationSpring Security 编程授权
【发布时间】: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


    【解决方案1】:

    我只是在使用一种解决方法:

    我已停用方法安全性,我只是将所有 Spring Data Endpoints 放在 /data/-prefixed 路由后面。然后我可以将 Spring Security 与所有不同的修改 HTTP 方法(POST、PUT、PATCH、DELETE)一起使用。

    【讨论】:

    • 虽然老实说,我对这个“解决方案”不是很满意。这会创建大量新的 antMatchers,但存在所有例外情况等。
    猜你喜欢
    • 2016-08-08
    • 2014-05-10
    • 2013-03-15
    • 2020-04-25
    • 2022-01-06
    • 2020-03-20
    • 2013-12-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多