Route proxy using authenticated client

This commit is contained in:
litoral05
2026-06-03 14:35:41 +01:00
parent 2203b0f2c3
commit 45419f23c1
3 changed files with 49 additions and 9 deletions
@@ -7,4 +7,5 @@ import java.util.Optional;
public interface ClientRepository extends JpaRepository<ClientEntity, Long> {
Optional<ClientEntity> findByName(String name);
Optional<ClientEntity> findByIdAndEnabledTrue(Long id);
}
@@ -0,0 +1,33 @@
package com.litoralregas.backend_gateway.client;
import com.litoralregas.backend_gateway.security.AuthenticatedUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
@Service
public class ClientResolver {
private final ClientRepository clientRepository;
public ClientResolver(ClientRepository clientRepository) {
this.clientRepository = clientRepository;
}
public ClientEntity resolveCurrentClient() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new RuntimeException("Not authenticated");
}
AuthenticatedUser user =
(AuthenticatedUser) authentication.getPrincipal();
return clientRepository
.findByIdAndEnabledTrue(user.clientId())
.orElseThrow(() -> new RuntimeException("Client not found"));
}
}
@@ -1,5 +1,6 @@
package com.litoralregas.backend_gateway.gateway;
import com.litoralregas.backend_gateway.client.ClientResolver;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
@@ -12,19 +13,18 @@ import org.springframework.web.reactive.function.client.WebClientResponseExcepti
public class BackendProxyService {
private final WebClient webClient;
private final ProxyProperties proxyProperties;
private final ClientResolver clientResolver;
public BackendProxyService(WebClient webClient, ProxyProperties proxyProperties) {
public BackendProxyService(
WebClient webClient,
ClientResolver clientResolver
) {
this.webClient = webClient;
this.proxyProperties = proxyProperties;
this.clientResolver = clientResolver;
}
public String getHealth() {
return webClient.get()
.uri(proxyProperties.getBackendBaseUrl() + "/actuator/health")
.retrieve()
.bodyToMono(String.class)
.block();
return "UP";
}
public ResponseEntity<String> proxy(HttpServletRequest request, String body) {
@@ -33,7 +33,7 @@ public class BackendProxyService {
String query = request.getQueryString();
String targetUrl =
proxyProperties.getBackendBaseUrl()
resolveBackendUrl()
+ path
+ (query != null ? "?" + query : "");
@@ -76,4 +76,10 @@ public class BackendProxyService {
.body("Backend unavailable");
}
}
private String resolveBackendUrl() {
return clientResolver
.resolveCurrentClient()
.getBackendBaseUrl();
}
}