Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/src/concepts/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,18 @@ app:
authentication:
jwt:
enabled: true
issuer-uri: ${OAUTH_ISSUER_URI:}
audiences: ${OAUTH_AUDIENCES:}
```

A valid signature only proves that the token comes from your identity provider. Set `OAUTH_ISSUER_URI` to the expected
`iss` claim and `OAUTH_AUDIENCES` to a comma-separated list of accepted `aud` values so that IDP-Core rejects tokens
issued for other applications of the same provider. Both settings are optional; IDP-Core logs a warning at startup
for each one that's missing.

When `jwt.enabled` is `false`, IDP-Core creates neither the JWT decoder nor the JWT chain, so `OAUTH_JWK_URI` isn't
required. You can disable Swagger independently with `app.security.swagger.enabled=false`. When you enable Swagger
required. When no authentication mode is enabled at all (`jwt`, `oauth2-login`, `api-key`, and `mock` are all
`false`), IDP-Core denies every request outside the public paths and the webhook entry point. You can disable Swagger independently with `app.security.swagger.enabled=false`. When you enable Swagger
without OAuth configuration, it publishes only the available security schemes.

#### Map IdP claims
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
package com.decathlon.idp_core.infrastructure.adapters.api.configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.JwtClaimNames;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

/// Custom JWT decoder configuration for OAuth2 resource server integration.
Expand All @@ -20,20 +32,63 @@
///
/// **Security considerations:** Maintains security while providing flexibility for various
/// identity provider implementations that may not follow all JWKS specifications exactly.
///
/// **Token binding:** a valid signature only proves that the token comes from the identity
/// provider, not that it was issued for this service. When
/// `app.security.authentication.jwt.issuer-uri` and/or `...jwt.audiences` are set, the `iss`
/// and `aud` claims are validated in addition to the signature and timestamps. Both are
/// optional for backward compatibility; a warning is logged at startup when either is missing.
@Configuration
@ConditionalOnProperty(prefix = "app.security.authentication.jwt", name = "enabled", havingValue = "true", matchIfMissing = false)
public class JwtConfiguration {

private static final Logger LOGGER = LoggerFactory.getLogger(JwtConfiguration.class);

private final String jwkSetUri;
private final String issuerUri;
private final List<String> audiences;

public JwtConfiguration(
@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}") String jwkSetUri) {
@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}") String jwkSetUri,
@Value("${app.security.authentication.jwt.issuer-uri:}") String issuerUri,
@Value("${app.security.authentication.jwt.audiences:}") String audiences) {
this.jwkSetUri = jwkSetUri;
this.issuerUri = issuerUri == null ? "" : issuerUri.trim();
this.audiences = audiences == null
? List.of()
: Arrays.stream(audiences.split(",")).map(String::trim).filter(a -> !a.isEmpty()).toList();
}

@Bean
@ConditionalOnMissingBean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
decoder.setJwtValidator(jwtValidator());
return decoder;
}

/// Builds the claim validators applied after signature verification.
///
/// Timestamps are always validated. The issuer is validated when configured,
/// and the token
/// must carry at least one of the configured audiences when any is configured.
OAuth2TokenValidator<Jwt> jwtValidator() {
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
if (issuerUri.isEmpty()) {
LOGGER.warn(
"app.security.authentication.jwt.issuer-uri is not set: the JWT issuer (iss) is not validated.");
validators.add(JwtValidators.createDefault());
} else {
validators.add(JwtValidators.createDefaultWithIssuer(issuerUri));
}
if (audiences.isEmpty()) {
LOGGER.warn(
"app.security.authentication.jwt.audiences is not set: the JWT audience (aud) is not validated, "
+ "tokens issued for other applications of the same identity provider are accepted.");
} else {
validators.add(new JwtClaimValidator<List<String>>(JwtClaimNames.AUD,
aud -> aud != null && aud.stream().anyMatch(audiences::contains)));
}
return new DelegatingOAuth2TokenValidator<>(validators);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

/// Fail-closed fallback applied when no authentication mode is enabled.
///
/// **Security rationale:** every authenticated chain (JWT, OAuth2 login, API key, mock) is
/// conditional on its own `app.security.authentication.*.enabled` flag, and only the public
/// and webhook chains declare a request matcher. Without this fallback, a deployment where
/// all flags are `false` leaves `/api/v1/**` outside every filter chain, which means the API
/// is served without authentication or authorization.
///
/// **Behaviour:** when none of the modes is enabled, this chain matches every request not
/// already handled by the public or webhook chains and denies it. It is not registered when
/// at least one mode is enabled, because those chains already match any request and Spring
/// Security rejects a chain declared after an any-request chain as unreachable.
@Configuration
@Conditional(FallbackDenyAllFilterChainConfig.NoAuthenticationModeEnabled.class)
public class FallbackDenyAllFilterChainConfig {

private static final Logger LOGGER = LoggerFactory
.getLogger(FallbackDenyAllFilterChainConfig.class);

@Bean
@Order(Ordered.LOWEST_PRECEDENCE)
public SecurityFilterChain fallbackDenyAllFilterChain(HttpSecurity http) {
LOGGER.warn(
"No authentication mode is enabled (app.security.authentication.[jwt|oauth2-login|api-key|mock].enabled). "
+ "All non-public requests will be denied.");
http.authorizeHttpRequests(auth -> auth.anyRequest().denyAll());
return http.build();
}

/// Matches when none of the authentication modes is switched on.
static class NoAuthenticationModeEnabled extends NoneNestedConditions {

NoAuthenticationModeEnabled() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}

@ConditionalOnProperty(prefix = "app.security.authentication.jwt", name = "enabled", havingValue = "true")
static class JwtEnabled {
}

@ConditionalOnProperty(prefix = "app.security.authentication.oauth2-login", name = "enabled", havingValue = "true")
static class OAuth2LoginEnabled {
}

@ConditionalOnProperty(prefix = "app.security.authentication.api-key", name = "enabled", havingValue = "true")
static class ApiKeyEnabled {
}

@ConditionalOnProperty(prefix = "app.security.authentication.mock", name = "enabled", havingValue = "true")
static class MockEnabled {
}
}
}
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ app:
authentication:
jwt:
enabled: true
# Expected `iss` claim. When set, tokens from any other issuer are rejected.
issuer-uri: ${OAUTH_ISSUER_URI:}
# Comma-separated accepted `aud` values. When set, a token must carry at least one of them,
# which rejects tokens issued by the same identity provider for other applications.
audiences: ${OAUTH_AUDIENCES:}
api-key:
enabled: false
mock:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.decathlon.idp_core.infrastructure.adapters.api.configuration;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.Instant;
import java.util.List;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;

@DisplayName("JwtConfigurationTest")
class JwtConfigurationTest {

private static final String JWKS = "https://idp.example.com/jwks.json";
private static final String ISSUER = "https://idp.example.com/";

@Test
void shouldAcceptAnyIssuerAndAudienceWhenNothingIsConfigured() {
var validator = new JwtConfiguration(JWKS, "", "").jwtValidator();

assertThat(
validator.validate(jwt("https://other.example.com/", List.of("other-app"))).hasErrors())
.isFalse();
}

@Test
void shouldRejectExpiredTokenEvenWhenNothingIsConfigured() {
var validator = new JwtConfiguration(JWKS, null, null).jwtValidator();
Jwt expired = Jwt.withTokenValue("t").header("alg", "RS256").issuer(ISSUER)
.issuedAt(Instant.now().minusSeconds(7200)).expiresAt(Instant.now().minusSeconds(3600))
.build();

assertThat(validator.validate(expired).hasErrors()).isTrue();
}

@Test
void shouldRejectTokenFromAnotherIssuerWhenIssuerIsConfigured() {
var validator = new JwtConfiguration(JWKS, ISSUER, "").jwtValidator();

assertThat(validator.validate(jwt(ISSUER, List.of("any"))).hasErrors()).isFalse();
assertThat(validator.validate(jwt("https://other.example.com/", List.of("any"))).hasErrors())
.isTrue();
}

@Test
void shouldRejectTokenForAnotherAudienceWhenAudiencesAreConfigured() {
var validator = new JwtConfiguration(JWKS, "", " idp-core , idp-core-cli ").jwtValidator();

assertThat(validator.validate(jwt(ISSUER, List.of("idp-core-cli"))).hasErrors()).isFalse();
assertThat(validator.validate(jwt(ISSUER, List.of("x", "idp-core"))).hasErrors()).isFalse();
assertThat(validator.validate(jwt(ISSUER, List.of("other-app"))).hasErrors()).isTrue();
}

@Test
void shouldRejectTokenWithoutAudienceWhenAudiencesAreConfigured() {
var validator = new JwtConfiguration(JWKS, "", "idp-core").jwtValidator();

OAuth2TokenValidatorResult result = validator.validate(jwt(ISSUER, null));

assertThat(result.hasErrors()).isTrue();
}

private static Jwt jwt(String issuer, List<String> audience) {
Jwt.Builder builder = Jwt.withTokenValue("t").header("alg", "RS256").issuer(issuer)
.issuedAt(Instant.now().minusSeconds(60)).expiresAt(Instant.now().plusSeconds(3600));
if (audience != null) {
builder.audience(audience);
}
return builder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.decathlon.idp_core.infrastructure.adapters.api.configuration.security.chains;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;

@DisplayName("FallbackDenyAllFilterChainConfigTest")
@ExtendWith(MockitoExtension.class)
class FallbackDenyAllFilterChainConfigTest {

@Mock
DefaultSecurityFilterChain securityFilterChain;

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FallbackDenyAllFilterChainConfig.class))
.withBean(HttpSecurity.class, this::httpSecurity);

@Test
void shouldCreateDenyAllChainWhenNoAuthenticationPropertyIsSet() {
contextRunner
.run(context -> assertThat(context).hasSingleBean(FallbackDenyAllFilterChainConfig.class)
.hasSingleBean(SecurityFilterChain.class));
}

@Test
void shouldCreateDenyAllChainWhenEveryModeIsExplicitlyDisabled() {
contextRunner
.withPropertyValues("app.security.authentication.jwt.enabled=false",
"app.security.authentication.oauth2-login.enabled=false",
"app.security.authentication.api-key.enabled=false",
"app.security.authentication.mock.enabled=false")
.run(context -> assertThat(context).hasSingleBean(FallbackDenyAllFilterChainConfig.class)
.hasSingleBean(SecurityFilterChain.class));
}

@ParameterizedTest
@ValueSource(strings = {"jwt", "oauth2-login", "api-key", "mock"})
void shouldNotCreateDenyAllChainWhenOneModeIsEnabled(String mode) {
contextRunner.withPropertyValues("app.security.authentication." + mode + ".enabled=true")
.run(context -> assertThat(context).doesNotHaveBean(FallbackDenyAllFilterChainConfig.class)
.doesNotHaveBean(SecurityFilterChain.class));
}

private HttpSecurity httpSecurity() {
HttpSecurity http = mock(HttpSecurity.class, org.mockito.Answers.RETURNS_DEEP_STUBS);
when(http.build()).thenReturn(securityFilterChain);
return http;
}
}
Loading