Skip to content

Instantly share code, notes, and snippets.

@mikaelhg
Last active May 4, 2022 06:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikaelhg/52e5a4d9d72f6b5411af to your computer and use it in GitHub Desktop.
Save mikaelhg/52e5a4d9d72f6b5411af to your computer and use it in GitHub Desktop.
Spring Boot @scheduled + Spring Security @PreAuthorize = RunAs
@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);
}
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment