1 package org
.argeo
.security
.core
;
3 import java
.security
.AccessController
;
5 import javax
.security
.auth
.Subject
;
7 import org
.argeo
.ArgeoException
;
8 import org
.argeo
.security
.SystemExecutionService
;
9 import org
.springframework
.core
.task
.SimpleAsyncTaskExecutor
;
10 import org
.springframework
.core
.task
.TaskExecutor
;
11 import org
.springframework
.security
.Authentication
;
12 import org
.springframework
.security
.AuthenticationManager
;
13 import org
.springframework
.security
.context
.SecurityContext
;
14 import org
.springframework
.security
.context
.SecurityContextHolder
;
16 public class KeyBasedSystemExecutionService
implements SystemExecutionService
,
18 private AuthenticationManager authenticationManager
;
19 private String systemAuthenticationKey
;
21 public void execute(Runnable runnable
) {
22 wrapWithSystemAuthentication(runnable
).run();
25 public TaskExecutor
createSystemAuthenticatedTaskExecutor() {
26 return new SimpleAsyncTaskExecutor() {
27 private static final long serialVersionUID
= -8126773862193265020L;
30 public Thread
createThread(Runnable runnable
) {
32 .createThread(wrapWithSystemAuthentication(runnable
));
38 protected Runnable
wrapWithSystemAuthentication(final Runnable runnable
) {
39 return new Runnable() {
42 SecurityContext securityContext
= SecurityContextHolder
44 Authentication currentAuth
= securityContext
46 if (currentAuth
!= null)
47 throw new ArgeoException(
48 "System execution on an already authenticated thread: "
49 + currentAuth
+ ", THREAD="
50 + Thread
.currentThread().getId());
52 Subject subject
= Subject
.getSubject(AccessController
55 && !subject
.getPrincipals(Authentication
.class)
57 throw new ArgeoException(
58 "There is already an authenticated subject: "
61 Authentication auth
= authenticationManager
62 .authenticate(new InternalAuthentication(
63 systemAuthenticationKey
));
64 securityContext
.setAuthentication(auth
);
68 // remove the authentication
69 securityContext
.setAuthentication(null);
75 public void setAuthenticationManager(
76 AuthenticationManager authenticationManager
) {
77 this.authenticationManager
= authenticationManager
;
80 public void setSystemAuthenticationKey(String systemAuthenticationKey
) {
81 this.systemAuthenticationKey
= systemAuthenticationKey
;