Last active
May 4, 2022 06:49
-
-
Save mikaelhg/52e5a4d9d72f6b5411af to your computer and use it in GitHub Desktop.
Spring Boot @scheduled + Spring Security @PreAuthorize = RunAs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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