]> git.argeo.org Git - lgpl/argeo-commons.git/blob - KeyBasedSystemExecutionService.java
a02221e323ce7dba34de0b03e46f5e5b8137948c
[lgpl/argeo-commons.git] / KeyBasedSystemExecutionService.java
1 package org.argeo.security.core;
2
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;
11
12 public class KeyBasedSystemExecutionService implements SystemExecutionService,
13 TaskExecutor {
14 private AuthenticationManager authenticationManager;
15 private String systemAuthenticationKey;
16
17 public void execute(Runnable runnable) {
18 wrapWithSystemAuthentication(runnable).run();
19 }
20
21 public TaskExecutor createSystemAuthenticatedTaskExecutor() {
22 return new SimpleAsyncTaskExecutor() {
23 private static final long serialVersionUID = -8126773862193265020L;
24
25 @Override
26 public Thread createThread(Runnable runnable) {
27 return super
28 .createThread(wrapWithSystemAuthentication(runnable));
29 }
30
31 };
32 }
33
34 protected Runnable wrapWithSystemAuthentication(final Runnable runnable) {
35 return new Runnable() {
36
37 public void run() {
38 SecurityContext securityContext = SecurityContextHolder
39 .getContext();
40 Authentication currentAuth = securityContext
41 .getAuthentication();
42 if (currentAuth != null) {
43 throw new ArgeoException(
44 "System execution on an already authenticated thread: "
45 + currentAuth + ", THREAD="
46 + Thread.currentThread().getId());
47 }
48 Authentication auth = authenticationManager
49 .authenticate(new InternalAuthentication(
50 systemAuthenticationKey));
51 securityContext.setAuthentication(auth);
52 try {
53 runnable.run();
54 } finally {
55 // remove the authentication
56 securityContext.setAuthentication(null);
57 }
58 }
59 };
60 }
61
62 public void setAuthenticationManager(
63 AuthenticationManager authenticationManager) {
64 this.authenticationManager = authenticationManager;
65 }
66
67 public void setSystemAuthenticationKey(String systemAuthenticationKey) {
68 this.systemAuthenticationKey = systemAuthenticationKey;
69 }
70
71 }