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
.springframework
.security
.Authentication
;
9 import org
.springframework
.security
.AuthenticationManager
;
10 import org
.springframework
.security
.context
.SecurityContext
;
11 import org
.springframework
.security
.context
.SecurityContextHolder
;
13 /** Provides base method for executing code with system authorization. */
14 public abstract class AbstractSystemExecution
{
15 private AuthenticationManager authenticationManager
;
16 private String systemAuthenticationKey
;
19 * Authenticate the calling thread to the underlying
20 * {@link AuthenticationManager}
22 protected void authenticateAsSystem() {
23 SecurityContext securityContext
= SecurityContextHolder
.getContext();
24 Authentication currentAuth
= securityContext
.getAuthentication();
25 if (currentAuth
!= null)
26 throw new ArgeoException(
27 "System execution on an already authenticated thread: "
28 + currentAuth
+ ", THREAD="
29 + Thread
.currentThread().getId());
31 Subject subject
= Subject
.getSubject(AccessController
.getContext());
33 && !subject
.getPrincipals(Authentication
.class).isEmpty())
34 throw new ArgeoException(
35 "There is already an authenticated subject: " + subject
);
37 String key
= systemAuthenticationKey
!= null ? systemAuthenticationKey
39 InternalAuthentication
.SYSTEM_KEY_PROPERTY
,
40 InternalAuthentication
.SYSTEM_KEY_DEFAULT
);
42 throw new ArgeoException("No system key defined");
43 Authentication auth
= authenticationManager
44 .authenticate(new InternalAuthentication(key
));
45 securityContext
.setAuthentication(auth
);
48 /** Removes the authentication from the calling thread. */
49 protected void deauthenticateAsSystem() {
50 // remove the authentication
51 SecurityContext securityContext
= SecurityContextHolder
.getContext();
52 securityContext
.setAuthentication(null);
55 public void setAuthenticationManager(
56 AuthenticationManager authenticationManager
) {
57 this.authenticationManager
= authenticationManager
;
60 public void setSystemAuthenticationKey(String systemAuthenticationKey
) {
61 this.systemAuthenticationKey
= systemAuthenticationKey
;