1 package org
.argeo
.security
.core
;
3 import java
.security
.AccessController
;
4 import java
.util
.concurrent
.Callable
;
5 import java
.util
.concurrent
.Executors
;
6 import java
.util
.concurrent
.Future
;
7 import java
.util
.concurrent
.FutureTask
;
9 import javax
.security
.auth
.Subject
;
11 import org
.argeo
.ArgeoException
;
12 import org
.argeo
.security
.SystemExecutionService
;
13 import org
.springframework
.security
.Authentication
;
14 import org
.springframework
.security
.AuthenticationManager
;
15 import org
.springframework
.security
.context
.SecurityContext
;
16 import org
.springframework
.security
.context
.SecurityContextHolder
;
19 * Implementation of a {@link SystemExecutionService} using a key-based
20 * {@link InternalAuthentication}
22 public class KeyBasedSystemExecutionService
implements SystemExecutionService
{
23 private AuthenticationManager authenticationManager
;
24 private String systemAuthenticationKey
;
26 public void execute(Runnable runnable
) {
28 wrapWithSystemAuthentication(Executors
.callable(runnable
)).call();
29 } catch (Exception e
) {
30 throw new ArgeoException(
31 "Exception when running system authenticated task", e
);
35 public <T
> Future
<T
> submit(Callable
<T
> task
) {
36 FutureTask
<T
> future
= new FutureTask
<T
>(
37 wrapWithSystemAuthentication(task
));
42 protected <T
> Callable
<T
> wrapWithSystemAuthentication(
43 final Callable
<T
> runnable
) {
44 return new Callable
<T
>() {
46 public T
call() throws Exception
{
47 SecurityContext securityContext
= SecurityContextHolder
49 Authentication currentAuth
= securityContext
51 if (currentAuth
!= null)
52 throw new ArgeoException(
53 "System execution on an already authenticated thread: "
54 + currentAuth
+ ", THREAD="
55 + Thread
.currentThread().getId());
57 Subject subject
= Subject
.getSubject(AccessController
60 && !subject
.getPrincipals(Authentication
.class)
62 throw new ArgeoException(
63 "There is already an authenticated subject: "
66 Authentication auth
= authenticationManager
67 .authenticate(new InternalAuthentication(
68 systemAuthenticationKey
));
69 securityContext
.setAuthentication(auth
);
71 return runnable
.call();
73 // remove the authentication
74 securityContext
.setAuthentication(null);
80 public void setAuthenticationManager(
81 AuthenticationManager authenticationManager
) {
82 this.authenticationManager
= authenticationManager
;
85 public void setSystemAuthenticationKey(String systemAuthenticationKey
) {
86 this.systemAuthenticationKey
= systemAuthenticationKey
;