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