【问题标题】:How to properly access a secured Spring Data REST Repository in a ApplicationRunner?如何在 ApplicationRunner 中正确访问安全的 Spring Data REST 存储库?
【发布时间】:2020-08-08 04:56:44
【问题描述】:

我关注了documentation,了解如何使用@PreAuthorize 保护 REST 存储库。但是,以下存储库

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RepositoryRestResource
public interface RouteRepository extends SortingOnlyRepository<Route, Long> {
}

需要通过ApplicationRunner 访问才能在应用程序启动后执行一些初始设置任务。

@Component
public class RouteBuilder implements ApplicationRunner {
    private final RouteRepository repository;

    public RouteBuilder(RouteRepository repository) {
        this.repository = repository;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        repository.findAll()
                .stream()
                // do something
                ;
    }
}

由于执行此运行程序时没有活动的安全上下文,因此应用程序根本不会启动

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException: Failed to execute ApplicationRunner
Caused by: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

正确访问 REST 存储库的选项有哪些?我在考虑

  • 填充 Authentication 就像 this
  • 解耦关注点,只是不要为此用例使用 REST 存储库
  • 单独在 WebSecurityConfig 中配置安全性

【问题讨论】:

    标签: java spring spring-data-rest


    【解决方案1】:

    问题的答案是填充适当的(假的)安全上下文,实际上在官方Spring Data REST + Spring Security 示例中给出。

    改编自Application

    try {
        SecurityUtils.runAs("system", "system", "ROLE_ADMIN");
    
        repository.findAll()
                    .stream()
                    // do something
                    ;
    } finally {
        SecurityContextHolder.clearContext();
    }
    

    SecurityUtils 在哪里

    public static void runAs(String username, String password, String... roles) {
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(username, password, AuthorityUtils.createAuthorityList(roles)));
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2017-04-30
      • 2015-06-23
      • 2020-06-17
      • 2017-10-18
      • 1970-01-01
      相关资源
      最近更新 更多