1 package org
.argeo
.security
.core
;
3 import org
.argeo
.ArgeoException
;
4 import org
.argeo
.security
.SystemExecutionService
;
5 import org
.springframework
.core
.task
.SimpleAsyncTaskExecutor
;
6 import org
.springframework
.core
.task
.TaskExecutor
;
7 import org
.springframework
.security
.Authentication
;
8 import org
.springframework
.security
.AuthenticationManager
;
9 import org
.springframework
.security
.context
.SecurityContext
;
10 import org
.springframework
.security
.context
.SecurityContextHolder
;
12 public class KeyBasedSystemExecutionService
implements SystemExecutionService
,
14 private AuthenticationManager authenticationManager
;
15 private String systemAuthenticationKey
;
17 public void execute(Runnable runnable
) {
18 wrapWithSystemAuthentication(runnable
).run();
21 public TaskExecutor
createSystemAuthenticatedTaskExecutor() {
22 return new SimpleAsyncTaskExecutor() {
23 private static final long serialVersionUID
= -8126773862193265020L;
26 public Thread
createThread(Runnable runnable
) {
28 .createThread(wrapWithSystemAuthentication(runnable
));
34 protected Runnable
wrapWithSystemAuthentication(final Runnable runnable
) {
35 return new Runnable() {
38 SecurityContext securityContext
= SecurityContextHolder
40 Authentication currentAuth
= securityContext
42 if (currentAuth
!= null) {
43 throw new ArgeoException(
44 "System execution on an already authenticated thread: "
45 + currentAuth
+ ", THREAD="
46 + Thread
.currentThread().getId());
48 Authentication auth
= authenticationManager
49 .authenticate(new InternalAuthentication(
50 systemAuthenticationKey
));
51 securityContext
.setAuthentication(auth
);
55 // remove the authentication
56 securityContext
.setAuthentication(null);
62 public void setAuthenticationManager(
63 AuthenticationManager authenticationManager
) {
64 this.authenticationManager
= authenticationManager
;
67 public void setSystemAuthenticationKey(String systemAuthenticationKey
) {
68 this.systemAuthenticationKey
= systemAuthenticationKey
;