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
3 changes: 3 additions & 0 deletions docs/context/session-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ Not limited. One account may hold several portal sessions, laptop sign-ins and a
- The back-channel session registry is in memory: this works with one backend replica.
- Any back-channel logout ends all of that user's portal sessions: Keycloak's user logout names only one session.
- Set `KEYCLOAK_REQUIRED_AUDIENCE` once all of a federation's clients issue tokens naming it in `aud`. Empty means `aud` is not checked; `azp` always is.
- DPoP for the laptop client: with `KEYCLOAK_CLI_REQUIRE_DPOP` on, the laptop client's (`mip-cli-<federation>`) tokens must be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `ath` — the SHA-256 of the access token, `iat`, replay and the token's `cnf.jkt` against the proof's key). Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location.
- Turn-on order: while the flag is off, a DPoP-bound token sent with `Bearer` is accepted without a proof (the binding is not enforced). With the flag on before clients send DPoP, every laptop user fails. Turn on Keycloak DPoP for the laptop client, this flag, and a DPoP-capable mip client release in one change window.
- The proof replay check keeps recent `jti` values in memory, per backend replica: with more than one replica, a proof can be replayed on another replica within the short `iat` window (it stays bound to one method and URL). Acceptable for now; use a shared cache if it matters later.

## Not available

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

Expand All @@ -16,7 +17,10 @@ public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) {
Authentication authentication = event.getAuthentication();
String username = authentication.getName();
Logger logger = new Logger(username, "LOGGING IN");
logger.info("User " + username + " has logged in successfully from " + remoteAddress(authentication));
// This event fires for every Bearer (and DPoP) request too, not only for portal sessions; the client
// tells the portal and the laptop client apart. Never the token, sid or jti.
logger.info("User " + username + " has logged in successfully from " + remoteAddress(authentication)
+ clientSuffix(authentication));

// If you need to log additional details:
authentication.getAuthorities().forEach(authority ->
Expand All @@ -43,6 +47,14 @@ static boolean isExpiredToken(Exception exception) {
return exception.getMessage() != null && exception.getMessage().contains("Jwt expired at");
}

static String clientSuffix(Authentication authentication) {
if (!(authentication instanceof JwtAuthenticationToken jwtAuthentication)) {
return "";
}
String client = jwtAuthentication.getToken().getClaimAsString("azp");
return " client=" + (client != null ? client : "none");
}

private static String remoteAddress(Authentication authentication) {
return authentication.getDetails() instanceof WebAuthenticationDetails details
? details.getRemoteAddress()
Expand Down
80 changes: 73 additions & 7 deletions src/main/java/hbp/mip/configurations/SecurityConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
Expand All @@ -24,6 +25,7 @@
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
Expand All @@ -43,6 +45,9 @@
import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.net.URI;
Expand Down Expand Up @@ -80,6 +85,11 @@ public class SecurityConfiguration {
@Value("${authentication.session_max_age:8h}")
private String sessionMaxAge;

// The public Keycloak client (device flow) of the mip client on users' own computers is named by the
// validator beans below; the chain itself only needs the DPoP flag.
@Value("${authentication.cli_require_dpop:false}")
private boolean cliRequireDpop;

@Value("${server.port:8080}")
private int serverPort;

Expand Down Expand Up @@ -123,8 +133,18 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http,

// Allow API clients (e.g. notebooks) to authenticate with Bearer JWTs.
// This runs alongside oauth2Login (session-based) authentication.
http.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter(keycloakClientId))));
http.oauth2ResourceServer(oauth2 -> {
oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter(keycloakClientId)));
if (cliRequireDpop) {
// Spring's DPoP filter takes "Authorization: DPoP <token>" plus a DPoP proof header and
// verifies the proof: its signature, htm/htu against this request, iat, jti replay and
// the token's cnf.jkt against the proof's key. It reads request.getRequestURL(), which
// the native forward-headers strategy builds from X-Forwarded-Proto/Host, so nginx must
// send those for the backend location (platform-ui's nginx.conf.template does not yet).
// ponytail: Spring keeps proof replays in an in-memory jti cache, one backend replica.
oauth2.dPoP(Customizer.withDefaults());
}
});

// Terms of use (NDA) apply to session and Bearer clients alike, not only to the portal UI.
http.addFilterAfter(new TermsOfUseFilter(activeUserService, handlerExceptionResolver, PUBLIC_PATHS),
Expand Down Expand Up @@ -165,7 +185,10 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http,
// Bearer-token clients should not need CSRF (they are not cookie-authenticated).
.ignoringRequestMatchers((request) -> {
String authz = request.getHeader("Authorization");
return authz != null && authz.startsWith("Bearer ");
// Same scheme-plus-space test for both: the request must actually carry a token,
// and one with an Authorization header is never cookie-authenticated.
return authz != null && (StringUtils.startsWithIgnoreCase(authz, "Bearer ")
|| StringUtils.startsWithIgnoreCase(authz, "DPoP "));
})
// Only this instance's own call: Spring's back-channel logout posts here without a token.
.ignoringRequestMatchers(SecurityConfiguration::isLocalLogout));
Expand Down Expand Up @@ -258,6 +281,43 @@ OAuth2TokenValidator<Jwt> requiredAudienceValidator(@Value("${authentication.req
return audienceValidator(audience);
}

// The laptop client's tokens must be DPoP-bound: Spring's DPoP filter verifies the proof, and this
// validator refuses a laptop-client token without the binding or one that arrives over the Bearer
// scheme. Platform-client tokens (portal, notebooks) stay Bearer. Only meaningful together with the
// dPoP() configurer above, which the same flag turns on.
@Bean
OAuth2TokenValidator<Jwt> cliDpopValidator(
@Value("${authentication.cli_client_id:}") String cliClientId,
@Value("${authentication.cli_require_dpop:false}") boolean requireDpop) {
return dpopValidator(cliClientId, requireDpop);
}

static OAuth2TokenValidator<Jwt> dpopValidator(String cliClientId, boolean requireDpop) {
return jwt -> !requireDpop || !StringUtils.hasText(cliClientId)
|| !cliClientId.equals(jwt.getClaimAsString("azp"))
|| (isDpopBound(jwt) && arrivedWithDpopScheme())
? OAuth2TokenValidatorResult.success()
: OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN,
"The laptop client's token must be DPoP-bound and used with the DPoP scheme", null));
}

private static boolean isDpopBound(Jwt jwt) {
Object confirmation = jwt.getClaims().get("cnf");
return confirmation instanceof Map<?, ?> claims && claims.get("jkt") != null;
}

// The validators only see the JWT; the request tells Bearer and DPoP apart. Spring Boot registers its
// RequestContextFilter before the security chain, so the request is in scope here; without it (tests)
// this fails closed.
static boolean arrivedWithDpopScheme() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (!(attributes instanceof ServletRequestAttributes servlet)) {
return false;
}
String authz = servlet.getRequest().getHeader("Authorization");
return authz != null && StringUtils.startsWithIgnoreCase(authz, OAuth2AccessToken.TokenType.DPOP.getValue());
}

static OAuth2TokenValidator<Jwt> audienceValidator(String audience) {
return jwt -> !StringUtils.hasText(audience) || (jwt.getAudience() != null && jwt.getAudience().contains(audience))
? OAuth2TokenValidatorResult.success()
Expand All @@ -266,12 +326,18 @@ static OAuth2TokenValidator<Jwt> audienceValidator(String audience) {
}

// Keycloak signs ID tokens with the same key and the same azp, so only its typ claim tells them from access tokens.
// DPoP-bound access tokens may carry typ "DPoP" instead of "Bearer" (RFC 9449); then cnf.jkt must be
// present, which is what makes such a token a bound access token and not an ID token. Keycloak's exact
// typ for DPoP tokens is still to be confirmed on a DPoP-enabled realm.
@Bean
OAuth2TokenValidator<Jwt> accessTokenValidator() {
return jwt -> "Bearer".equals(jwt.getClaimAsString("typ"))
? OAuth2TokenValidatorResult.success()
: OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN,
"The token is not an access token", null));
return jwt -> {
String typ = jwt.getClaimAsString("typ");
return "Bearer".equals(typ) || ("DPoP".equals(typ) && isDpopBound(jwt))
? OAuth2TokenValidatorResult.success()
: OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN,
"The token is not an access token", null));
};
}

static JwtAuthenticationConverter jwtAuthenticationConverter(String clientId) {
Expand Down
3 changes: 3 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ authentication:
cli_client_id: ${KEYCLOAK_CLI_CLIENT_ID:}
# When set, Bearer tokens must also name this in aud; set it once every client's tokens do.
required_audience: ${KEYCLOAK_REQUIRED_AUDIENCE:}
# Require the laptop client's tokens to be DPoP-bound (RFC 9449) and used with the DPoP scheme.
# Turn on once Keycloak and the mip client have switched; remove once every federation has.
cli_require_dpop: ${KEYCLOAK_CLI_REQUIRE_DPOP:false}
# Portal sessions end at this age however active they are (8h or PT8H).
session_max_age: ${SESSION_MAX_AGE:8h}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import java.util.List;

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

Expand All @@ -16,4 +20,22 @@ void onlyAnExpiredTokenCountsAsRoutine() {
"An error occurred while attempting to decode the Jwt: Signed JWT rejected"))).isFalse();
assertThat(AuthenticationEventListener.isExpiredToken(new BadCredentialsException(null))).isFalse();
}

@Test
void aBearerLoginLogsItsClientButNeverTheToken() {
Jwt token = Jwt.withTokenValue("token-value-never-log")
.header("alg", "RS256")
.claim("azp", "mip-cli-x")
.build();
JwtAuthenticationToken authentication = new JwtAuthenticationToken(token, List.of());

assertThat(AuthenticationEventListener.clientSuffix(authentication)).isEqualTo(" client=mip-cli-x");
}

@Test
void aJwtWithoutAClientLogsNone() {
Jwt token = Jwt.withTokenValue("t").header("alg", "RS256").claim("sub", "alice").build();
assertThat(AuthenticationEventListener.clientSuffix(new JwtAuthenticationToken(token, List.of())))
.isEqualTo(" client=none");
}
}
Loading
Loading