]> git.argeo.org Git - lgpl/argeo-commons.git/blob - security/runtime/org.argeo.security.core/src/main/java/org/argeo/security/core/AbstractSystemExecution.java
Introduce system authenticated bean post processing
[lgpl/argeo-commons.git] / security / runtime / org.argeo.security.core / src / main / java / org / argeo / security / core / AbstractSystemExecution.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.springframework.security.Authentication;
9 import org.springframework.security.AuthenticationManager;
10 import org.springframework.security.context.SecurityContext;
11 import org.springframework.security.context.SecurityContextHolder;
12
13 /** Provides base method for executing code with system authorization. */
14 public abstract class AbstractSystemExecution {
15 private AuthenticationManager authenticationManager;
16 private String systemAuthenticationKey;
17
18 /**
19 * Authenticate the calling thread to the underlying
20 * {@link AuthenticationManager}
21 */
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());
30
31 Subject subject = Subject.getSubject(AccessController.getContext());
32 if (subject != null
33 && !subject.getPrincipals(Authentication.class).isEmpty())
34 throw new ArgeoException(
35 "There is already an authenticated subject: " + subject);
36
37 String key = systemAuthenticationKey != null ? systemAuthenticationKey
38 : System.getProperty(
39 InternalAuthentication.SYSTEM_KEY_PROPERTY,
40 InternalAuthentication.SYSTEM_KEY_DEFAULT);
41 if (key == null)
42 throw new ArgeoException("No system key defined");
43 Authentication auth = authenticationManager
44 .authenticate(new InternalAuthentication(key));
45 securityContext.setAuthentication(auth);
46 }
47
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);
53 }
54
55 public void setAuthenticationManager(
56 AuthenticationManager authenticationManager) {
57 this.authenticationManager = authenticationManager;
58 }
59
60 public void setSystemAuthenticationKey(String systemAuthenticationKey) {
61 this.systemAuthenticationKey = systemAuthenticationKey;
62 }
63
64 }