diff --git a/AGENTS.md b/AGENTS.md
index e6ad2b7..5bd50c3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,6 +44,8 @@ kubectl port-forward svc/api-gateway 8080:8080 -n digital-bank-sit
- Centralized Swagger/OpenAPI access should be exposed here, not by telling users to hit each downstream service directly.
- Admin documentation routes are internal tooling and should stay clearly separated from public customer APIs.
+- Gateway authorization is feature-flagged with `gateway.security.enabled`; SIT enables it through Helm and injects the JWT secret from Kubernetes Secret.
+- Keep JWT validation at the gateway aligned with downstream scopes: `admin.internal`, `mfa.internal`, `transaction.internal`, and `payment.internal`.
## Working Rules
diff --git a/README.md b/README.md
index 70141d2..c8dabc5 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Spring Cloud Gateway entry point for the Digital Bank Java platform.
- Business-domain logic.
- Persistence.
- Service discovery through Eureka.
-- Authentication implementation in the initial slice.
+- Domain authentication and token issuance. The gateway validates bearer tokens and applies route-level authorization.
## Runtime Model
@@ -114,6 +114,21 @@ The centralized internal API documentation UI is available at:
http://localhost:8080/admin/docs/swagger-ui.html
```
+## Gateway Authorization And Environment Promotion
+
+The gateway is an internal Kubernetes `ClusterIP` Service in SIT. When `gateway.security.enabled` is true, it validates JWTs and enforces these scopes:
+
+- `admin.internal` for `/admin/**` and centralized API documentation.
+- `mfa.internal` for `/api/v1/mfa/**`.
+- `transaction.internal` for `/internal/v1/transfer-workflows/**`.
+- `payment.internal` for `/internal/v1/payment-instructions/**`.
+
+Customer and account APIs require an authenticated token. Health endpoints and Auth login remain public. Requests that do not authenticate receive `401` Problem Details; authenticated requests without the required scope receive `403` Problem Details.
+
+SIT uses a base64-encoded HMAC secret supplied through the Kubernetes `auth-service-secrets` Secret. UAT and PROD should use the same application contract with an AWS-managed secret or an OIDC/JWK issuer; no token secret belongs in Git. The chart keeps security disabled by default outside an explicitly enabled environment.
+
+Circuit breaking and safe-read retries are independent availability controls. They do not replace service authorization, idempotency keys, transactional guarantees, or audit controls.
+
## Redis-backed Rate Limiting
Public customer and account routes in SIT use the shared Redis service for route-level token-bucket limits. The current SIT policy allows 10 requested tokens per second with a burst capacity of 20 and one token per request. Requests that exceed the available bucket receive `429 Too Many Requests`.
@@ -128,7 +143,7 @@ The gateway applies a fail-closed policy to Redis rate-limit errors. Spring Clou
## Security And Environment Promotion
-The gateway is an internal Kubernetes `ClusterIP` Service in SIT. Circuit breaking, safe-read retries, and Redis-backed rate limiting are implemented as cross-cutting availability controls. Authentication, authorization, and correlation propagation remain planned capabilities.
+The gateway is an internal Kubernetes `ClusterIP` Service in SIT. Circuit breaking, safe-read retries, Redis-backed rate limiting, authentication, and authorization are cross-cutting controls. They do not replace service-level idempotency, transactional guarantees, or audit controls.
## Downstream Resilience
diff --git a/helm/templates/deployment.yaml b/helm/templates/deployment.yaml
index e03f144..f3e20f6 100644
--- a/helm/templates/deployment.yaml
+++ b/helm/templates/deployment.yaml
@@ -37,6 +37,15 @@ spec:
value: {{ .Values.runtime.configServerUrl | quote }}
- name: SPRING_PROFILES_ACTIVE
value: {{ .Values.runtime.profile | quote }}
+ - name: GATEWAY_SECURITY_ENABLED
+ value: {{ .Values.security.enabled | quote }}
+ {{- if .Values.security.enabled }}
+ - name: AUTH_JWT_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.security.secretName | quote }}
+ key: {{ .Values.security.secretKey | quote }}
+ {{- end }}
securityContext:
{{- toYaml .Values.containerSecurityContext | nindent 12 }}
ports:
diff --git a/helm/values-sit.yaml b/helm/values-sit.yaml
index 91fdc96..9f8a843 100644
--- a/helm/values-sit.yaml
+++ b/helm/values-sit.yaml
@@ -1,3 +1,6 @@
runtime:
profile: sit
configServerUrl: http://config-server:8888
+
+security:
+ enabled: true
diff --git a/helm/values.yaml b/helm/values.yaml
index 8f18ad7..5ede1b2 100644
--- a/helm/values.yaml
+++ b/helm/values.yaml
@@ -12,6 +12,11 @@ runtime:
profile: sit
configServerUrl: http://config-server:8888
+security:
+ enabled: false
+ secretName: auth-service-secrets
+ secretKey: jwt-secret
+
service:
type: ClusterIP
port: 8080
diff --git a/pom.xml b/pom.xml
index f4a5157..1a5afda 100644
--- a/pom.xml
+++ b/pom.xml
@@ -39,6 +39,14 @@
org.springframework.cloud
spring-cloud-starter-circuitbreaker-reactor-resilience4j
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-resource-server
+
org.springdoc
springdoc-openapi-starter-webflux-ui
diff --git a/src/main/java/com/digitalbank/apigateway/security/GatewayJwtDecoderConfiguration.java b/src/main/java/com/digitalbank/apigateway/security/GatewayJwtDecoderConfiguration.java
new file mode 100644
index 0000000..c860c60
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/security/GatewayJwtDecoderConfiguration.java
@@ -0,0 +1,76 @@
+package com.digitalbank.apigateway.security;
+
+import java.util.Base64;
+
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
+import org.springframework.security.oauth2.core.OAuth2TokenValidator;
+import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.security.oauth2.jwt.JwtValidators;
+import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
+import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
+import org.springframework.security.oauth2.jwt.ReactiveJwtDecoders;
+import org.springframework.util.StringUtils;
+
+@Configuration(proxyBeanMethods = false)
+@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
+class GatewayJwtDecoderConfiguration {
+
+ private static final int MINIMUM_HMAC_KEY_BYTES = 32;
+
+ @Bean
+ @ConditionalOnMissingBean(ReactiveJwtDecoder.class)
+ ReactiveJwtDecoder gatewayReactiveJwtDecoder(
+ @Value("${auth.jwt.issuer:}") String issuer,
+ @Value("${auth.jwt.secret:}") String secret,
+ @Value("${auth.jwt.jwk-set-uri:}") String jwkSetUri) {
+ if (StringUtils.hasText(secret)) {
+ return hmacDecoder(secret, issuer);
+ }
+ if (StringUtils.hasText(jwkSetUri)) {
+ return jwkDecoder(jwkSetUri, issuer);
+ }
+ if (StringUtils.hasText(issuer)) {
+ return ReactiveJwtDecoders.fromIssuerLocation(issuer);
+ }
+ throw new IllegalStateException(
+ "Gateway security is enabled but no auth.jwt.secret, auth.jwt.jwk-set-uri, or auth.jwt.issuer is configured");
+ }
+
+ private ReactiveJwtDecoder hmacDecoder(String encodedSecret, String issuer) {
+ final byte[] secret;
+ try {
+ secret = Base64.getDecoder().decode(encodedSecret);
+ } catch (IllegalArgumentException exception) {
+ throw new IllegalStateException("auth.jwt.secret must be a valid Base64 value", exception);
+ }
+ if (secret.length < MINIMUM_HMAC_KEY_BYTES) {
+ throw new IllegalStateException("auth.jwt.secret must decode to at least 32 bytes");
+ }
+ return configuredDecoder(new SecretKeySpec(secret, "HmacSHA256"), issuer);
+ }
+
+ private ReactiveJwtDecoder jwkDecoder(String jwkSetUri, String issuer) {
+ NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();
+ if (StringUtils.hasText(issuer)) {
+ decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(issuer));
+ }
+ return decoder;
+ }
+
+ private ReactiveJwtDecoder configuredDecoder(SecretKey key, String issuer) {
+ NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(key).build();
+ if (StringUtils.hasText(issuer)) {
+ OAuth2TokenValidator issuerValidator = JwtValidators.createDefaultWithIssuer(issuer);
+ decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(issuerValidator));
+ }
+ return decoder;
+ }
+}
diff --git a/src/main/java/com/digitalbank/apigateway/security/GatewayProblemDetailsWriter.java b/src/main/java/com/digitalbank/apigateway/security/GatewayProblemDetailsWriter.java
new file mode 100644
index 0000000..9d52475
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/security/GatewayProblemDetailsWriter.java
@@ -0,0 +1,52 @@
+package com.digitalbank.apigateway.security;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.ObjectMapper;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatusCode;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ServerWebExchange;
+
+import reactor.core.publisher.Mono;
+
+@Component
+@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
+final class GatewayProblemDetailsWriter {
+
+ private final ObjectMapper objectMapper;
+
+ GatewayProblemDetailsWriter(ObjectMapper objectMapper) {
+ this.objectMapper = objectMapper;
+ }
+
+ Mono write(ServerWebExchange exchange, int status, String title, String detail,
+ boolean includeAuthenticateHeader) {
+ exchange.getResponse().setStatusCode(HttpStatusCode.valueOf(status));
+ exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_PROBLEM_JSON);
+ if (includeAuthenticateHeader) {
+ exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
+ }
+
+ Map problem = new LinkedHashMap<>();
+ problem.put("type", "https://digital-bank-java.local/problems/authorization-error");
+ problem.put("title", title);
+ problem.put("status", status);
+ problem.put("detail", detail);
+ problem.put("instance", exchange.getRequest().getPath().value());
+
+ final byte[] body;
+ try {
+ body = objectMapper.writeValueAsBytes(problem);
+ } catch (JacksonException exception) {
+ return Mono.error(exception);
+ }
+ var buffer = exchange.getResponse().bufferFactory().wrap(body);
+ return exchange.getResponse().writeWith(Mono.just(buffer));
+ }
+}
diff --git a/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityConfiguration.java b/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityConfiguration.java
new file mode 100644
index 0000000..a5eb66a
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityConfiguration.java
@@ -0,0 +1,76 @@
+package com.digitalbank.apigateway.security;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
+import org.springframework.security.config.web.server.ServerHttpSecurity;
+import org.springframework.security.web.server.SecurityWebFilterChain;
+import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
+import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
+
+import static org.springframework.security.config.Customizer.withDefaults;
+
+@Configuration(proxyBeanMethods = false)
+@EnableWebFluxSecurity
+@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "true")
+class GatewaySecurityConfiguration {
+
+ @Bean
+ SecurityWebFilterChain gatewaySecurityWebFilterChain(ServerHttpSecurity http,
+ ServerAuthenticationEntryPoint authenticationEntryPoint,
+ ServerAccessDeniedHandler accessDeniedHandler) {
+ return http
+ .csrf(ServerHttpSecurity.CsrfSpec::disable)
+ .authorizeExchange(authorize -> authorize
+ .pathMatchers(
+ "/actuator/health/**",
+ "/actuator/info",
+ "/auth-service/actuator/health/**",
+ "/account-service/actuator/health/**",
+ "/config-server/actuator/health/**",
+ "/customer-service/actuator/health/**",
+ "/ledger-service/actuator/health/**",
+ "/mfa-service/actuator/health/**",
+ "/notification-service/actuator/health/**",
+ "/payment-service/actuator/health/**",
+ "/transaction-service/actuator/health/**",
+ "/error",
+ "/api/v1/auth/login")
+ .permitAll()
+ .pathMatchers("/api/v1/auth/**")
+ .authenticated()
+ .pathMatchers(
+ "/admin/**",
+ "/v3/api-docs/swagger-config",
+ "/swagger-ui/**",
+ "/swagger-ui.html")
+ .hasAuthority("SCOPE_admin.internal")
+ .pathMatchers("/api/v1/mfa/**")
+ .hasAuthority("SCOPE_mfa.internal")
+ .pathMatchers("/internal/v1/transfer-workflows", "/internal/v1/transfer-workflows/**")
+ .hasAuthority("SCOPE_transaction.internal")
+ .pathMatchers("/internal/v1/payment-instructions", "/internal/v1/payment-instructions/**")
+ .hasAuthority("SCOPE_payment.internal")
+ .pathMatchers("/api/v1/customers/**", "/api/v1/accounts/**")
+ .authenticated()
+ .anyExchange().denyAll())
+ .oauth2ResourceServer(oauth2 -> oauth2
+ .jwt(withDefaults())
+ .authenticationEntryPoint(authenticationEntryPoint)
+ .accessDeniedHandler(accessDeniedHandler))
+ .build();
+ }
+
+ @Bean
+ ServerAuthenticationEntryPoint gatewayAuthenticationEntryPoint(GatewayProblemDetailsWriter writer) {
+ return (exchange, exception) -> writer.write(exchange, 401, "Authentication required",
+ "A valid bearer token is required to access this resource.", true);
+ }
+
+ @Bean
+ ServerAccessDeniedHandler gatewayAccessDeniedHandler(GatewayProblemDetailsWriter writer) {
+ return (exchange, exception) -> writer.write(exchange, 403, "Access denied",
+ "The bearer token does not grant the required scope for this resource.", false);
+ }
+}
diff --git a/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityDisabledConfiguration.java b/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityDisabledConfiguration.java
new file mode 100644
index 0000000..e3fe399
--- /dev/null
+++ b/src/main/java/com/digitalbank/apigateway/security/GatewaySecurityDisabledConfiguration.java
@@ -0,0 +1,20 @@
+package com.digitalbank.apigateway.security;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.web.server.ServerHttpSecurity;
+import org.springframework.security.web.server.SecurityWebFilterChain;
+
+@Configuration(proxyBeanMethods = false)
+@ConditionalOnProperty(name = "gateway.security.enabled", havingValue = "false", matchIfMissing = true)
+class GatewaySecurityDisabledConfiguration {
+
+ @Bean
+ SecurityWebFilterChain gatewaySecurityDisabledWebFilterChain(ServerHttpSecurity http) {
+ return http
+ .csrf(ServerHttpSecurity.CsrfSpec::disable)
+ .authorizeExchange(authorize -> authorize.anyExchange().permitAll())
+ .build();
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index c9b0528..1625d54 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -25,6 +25,8 @@ spring:
response-timeout: ${gateway.resilience.timeout.response-timeout:2s}
gateway:
+ security:
+ enabled: ${GATEWAY_SECURITY_ENABLED:false}
rate-limit:
trusted-proxies: []
resilience:
@@ -46,6 +48,12 @@ gateway:
permitted-number-of-calls-in-half-open-state: 2
automatic-transition-from-open-to-half-open-enabled: true
+auth:
+ jwt:
+ issuer: ${AUTH_JWT_ISSUER:}
+ secret: ${AUTH_JWT_SECRET:}
+ jwk-set-uri: ${AUTH_JWT_JWK_SET_URI:}
+
resilience4j:
circuitbreaker:
configs:
diff --git a/src/test/java/com/digitalbank/apigateway/GatewaySecurityIntegrationTests.java b/src/test/java/com/digitalbank/apigateway/GatewaySecurityIntegrationTests.java
new file mode 100644
index 0000000..a318e32
--- /dev/null
+++ b/src/test/java/com/digitalbank/apigateway/GatewaySecurityIntegrationTests.java
@@ -0,0 +1,89 @@
+package com.digitalbank.apigateway;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.test.web.reactive.server.WebTestClient;
+
+import java.time.Instant;
+
+import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
+
+import reactor.core.publisher.Mono;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
+ "spring.config.import=",
+ "spring.cloud.config.enabled=false",
+ "gateway.security.enabled=true",
+ "auth.jwt.issuer=https://issuer.test",
+ "management.health.redis.enabled=false" })
+@Import(GatewaySecurityIntegrationTests.TestJwtConfiguration.class)
+class GatewaySecurityIntegrationTests {
+
+ @Value("${local.server.port}")
+ private int port;
+
+ private WebTestClient client;
+
+ @BeforeEach
+ void setUp() {
+ client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
+ }
+
+ @Test
+ void adminRouteWithoutBearerTokenReturnsProblemDetailsUnauthorized() {
+ client.get()
+ .uri("/admin/v1/customers")
+ .exchange()
+ .expectStatus().isUnauthorized()
+ .expectHeader().contentType("application/problem+json")
+ .expectHeader().valueEquals("WWW-Authenticate", "Bearer")
+ .expectBody()
+ .jsonPath("$.status").isEqualTo(401)
+ .jsonPath("$.title").isEqualTo("Authentication required")
+ .jsonPath("$.instance").isEqualTo("/admin/v1/customers");
+ }
+
+ @Test
+ void adminRouteWithInsufficientScopeReturnsProblemDetailsForbidden() {
+ client.get()
+ .uri("/admin/v1/customers")
+ .headers(headers -> headers.setBearerAuth("wrong-scope"))
+ .exchange()
+ .expectStatus().isForbidden()
+ .expectHeader().contentType("application/problem+json")
+ .expectBody()
+ .jsonPath("$.status").isEqualTo(403)
+ .jsonPath("$.title").isEqualTo("Access denied")
+ .jsonPath("$.instance").isEqualTo("/admin/v1/customers");
+ }
+
+ @Test
+ void healthEndpointRemainsPublicWhenGatewaySecurityIsEnabled() {
+ client.get()
+ .uri("/actuator/health")
+ .exchange()
+ .expectStatus().isOk()
+ .expectBody()
+ .jsonPath("$.status").isEqualTo("UP");
+ }
+
+ @TestConfiguration(proxyBeanMethods = false)
+ static final class TestJwtConfiguration {
+
+ @Bean
+ ReactiveJwtDecoder reactiveJwtDecoder() {
+ return token -> Mono.just(Jwt.withTokenValue(token)
+ .header("alg", "none")
+ .claim("scope", "wrong.scope")
+ .issuedAt(Instant.now())
+ .expiresAt(Instant.now().plusSeconds(300))
+ .build());
+ }
+ }
+}