8
8
package org .sdase .commons .spring .boot .web .auth .management ;
9
9
10
10
import java .util .Collection ;
11
- import java .util .Optional ;
12
11
import org .springframework .boot .actuate .autoconfigure .web .server .ConditionalOnManagementPort ;
13
12
import org .springframework .boot .actuate .autoconfigure .web .server .ManagementPortType ;
14
- import org .springframework .boot .web .servlet .context .ServletWebServerApplicationContext ;
15
- import org .springframework .context .annotation . Lazy ;
13
+ import org .springframework .boot .web .servlet .context .ServletWebServerInitializedEvent ;
14
+ import org .springframework .context .event . EventListener ;
16
15
import org .springframework .security .access .AccessDecisionVoter ;
17
16
import org .springframework .security .access .ConfigAttribute ;
18
17
import org .springframework .security .core .Authentication ;
@@ -35,24 +34,27 @@ default boolean supports(Class<?> clazz) {
35
34
@ ConditionalOnManagementPort (ManagementPortType .DIFFERENT )
36
35
class DifferentPortManagementAccessDecisionVoter implements ManagementAccessDecisionVoter {
37
36
38
- private final ServletWebServerApplicationContext apiServerContext ;
37
+ /**
38
+ * The management port discovered in {@link
39
+ * #onApplicationEvent(ServletWebServerInitializedEvent)}. Initially a value that can't be an
40
+ * existing port to avoid granting access by accident to the application API.
41
+ */
42
+ private int managementPort = -1 ;
39
43
40
- public DifferentPortManagementAccessDecisionVoter (
41
- @ Lazy Optional <ServletWebServerApplicationContext > apiServerContext ) {
42
- this .apiServerContext = apiServerContext .orElse (null );
44
+ @ EventListener
45
+ public void onApplicationEvent (ServletWebServerInitializedEvent event ) {
46
+ if ("management" .equals (event .getApplicationContext ().getServerNamespace ())) {
47
+ this .managementPort = event .getWebServer ().getPort ();
48
+ }
43
49
}
44
50
45
51
@ Override
46
52
public int vote (
47
53
Authentication authentication ,
48
54
FilterInvocation filterInvocation ,
49
55
Collection <ConfigAttribute > attributes ) {
50
- return apiServerContext != null
51
- && filterInvocation .getRequest ().getLocalPort ()
52
- // TODO would be nice to get the real management port - also when the config is 0
53
- != apiServerContext .getWebServer ().getPort ()
54
- ? ACCESS_GRANTED
55
- : ACCESS_ABSTAIN ;
56
+ int requestLocalPort = filterInvocation .getRequest ().getLocalPort ();
57
+ return requestLocalPort == this .managementPort ? ACCESS_GRANTED : ACCESS_ABSTAIN ;
56
58
}
57
59
}
58
60
0 commit comments