java Spring Boot @Scheduled + Spring Security @PreAuthorize = RunAs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Spring Boot @Scheduled + Spring Security @PreAuthorize = RunAs相关的知识,希望对你有一定的参考价值。

package io.mikael;

import com.google.common.collect.ImmutableList;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class RunAs {

    @FunctionalInterface
    public interface RunAsMethod {
        default void run() {
            try {
                runWithException();
            } catch (Exception e) {
                // ignore
            }
        }
        void runWithException() throws Exception;
    }

    public static void runAsAdmin(final RunAsMethod func) {
        final AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("system", "system",
                ImmutableList.of(new SimpleGrantedAuthority("ROLE_ADMIN")));
        final Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityContextHolder.getContext().setAuthentication(token);
        func.run();
        SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
    }

}

@Service
class FooService {
    @Inject FooDao dao;
    
    @Scheduled(fixedRate = 600000L, initialDelay = 60000L)
    public void periodicalTask() throws IOException {
        RunAs.runAsAdmin(() -> {
            dao.save(new Foo(...));
        });
    }
}


@RepositoryRestResource(path = "notices")
public interface FooDao extends JpaRepository<Foo, String> {

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    <S extends Foo> S save(S entity);
    
}

以上是关于java Spring Boot @Scheduled + Spring Security @PreAuthorize = RunAs的主要内容,如果未能解决你的问题,请参考以下文章

确保Spring Quartz作业执行不重叠

Spring Boot 各版本的Java版本要求

Spring Boot . 2 -- 用Spring Boot 创建一个Java Web 应用

如何 JUnit 测试 Spring-Boot 的 Application.java

markdown Spring Boot #SpringBoot #Spring #Java

小马哥-Java 微服务实践 - Spring Boot 系列-01Java 微服务实践 - Spring Boot 系列初体验