Skip to content

Commit d7b8a29

Browse files
committed
fix: identify the real management port
1 parent 826dc64 commit d7b8a29

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

sda-commons-web-autoconfigure/src/main/java/org/sdase/commons/spring/boot/web/auth/management/ManagementAccessDecisionVoter.java

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@
88
package org.sdase.commons.spring.boot.web.auth.management;
99

1010
import java.util.Collection;
11-
import java.util.Optional;
1211
import org.springframework.boot.actuate.autoconfigure.web.server.ConditionalOnManagementPort;
1312
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;
1615
import org.springframework.security.access.AccessDecisionVoter;
1716
import org.springframework.security.access.ConfigAttribute;
1817
import org.springframework.security.core.Authentication;
@@ -35,24 +34,27 @@ default boolean supports(Class<?> clazz) {
3534
@ConditionalOnManagementPort(ManagementPortType.DIFFERENT)
3635
class DifferentPortManagementAccessDecisionVoter implements ManagementAccessDecisionVoter {
3736

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;
3943

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+
}
4349
}
4450

4551
@Override
4652
public int vote(
4753
Authentication authentication,
4854
FilterInvocation filterInvocation,
4955
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;
5658
}
5759
}
5860

0 commit comments

Comments
 (0)