Skip to content

Commit 4dc75bf

Browse files
committed
Send saml logout response even when validation errors happen
1 parent bade66e commit 4dc75bf

File tree

7 files changed

+288
-62
lines changed

7 files changed

+288
-62
lines changed

saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2ErrorCodes.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -130,6 +130,30 @@ public final class Saml2ErrorCodes {
130130
*/
131131
public static final String INVALID_IN_RESPONSE_TO = "invalid_in_response_to";
132132

133+
/**
134+
* The RP registration does not have configured a logout request endpoint
135+
* @since 6.3
136+
*/
137+
public static final String MISSING_LOGOUT_REQUEST_ENDPOINT = "missing_logout_request_endpoint";
138+
139+
/**
140+
* The saml response or logout request was delivered via an invalid binding
141+
* @since 6.3
142+
*/
143+
public static final String INVALID_BINDING = "invalid_binding";
144+
145+
/**
146+
* The saml logout request failed validation
147+
* @since 6.3
148+
*/
149+
public static final String INVALID_LOGOUT_REQUEST = "invalid_logout_request";
150+
151+
/**
152+
* The saml logout response could not be generated
153+
* @since 6.3
154+
*/
155+
public static final String FAILED_TO_GENERATE_LOGOUT_RESPONSE = "failed_to_generate_logout_response";
156+
133157
private Saml2ErrorCodes() {
134158
}
135159

saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -22,8 +22,12 @@
2222

2323
import jakarta.servlet.http.HttpServletRequest;
2424
import org.opensaml.saml.saml2.core.LogoutResponse;
25+
import org.opensaml.saml.saml2.core.StatusCode;
2526

2627
import org.springframework.security.core.Authentication;
28+
import org.springframework.security.saml2.core.Saml2Error;
29+
import org.springframework.security.saml2.core.Saml2ErrorCodes;
30+
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
2731
import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse;
2832
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
2933
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
@@ -67,11 +71,26 @@ public OpenSaml4LogoutResponseResolver(RelyingPartyRegistrationResolver relyingP
6771
*/
6872
@Override
6973
public Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication) {
70-
return this.logoutResponseResolver.resolve(request, authentication, (registration, logoutResponse) -> {
71-
logoutResponse.setIssueInstant(Instant.now(this.clock));
72-
this.parametersConsumer
73-
.accept(new LogoutResponseParameters(request, registration, authentication, logoutResponse));
74-
});
74+
return this.logoutResponseResolver.resolve(request, authentication, StatusCode.SUCCESS,
75+
(registration, logoutResponse) -> {
76+
logoutResponse.setIssueInstant(Instant.now(this.clock));
77+
this.parametersConsumer
78+
.accept(new LogoutResponseParameters(request, registration, authentication, logoutResponse));
79+
});
80+
}
81+
82+
/**
83+
* {@inheritDoc}
84+
*/
85+
@Override
86+
public Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication,
87+
Saml2AuthenticationException exception) {
88+
return this.logoutResponseResolver.resolve(request, authentication, getSamlStatus(exception),
89+
(registration, logoutResponse) -> {
90+
logoutResponse.setIssueInstant(Instant.now(this.clock));
91+
this.parametersConsumer
92+
.accept(new LogoutResponseParameters(request, registration, authentication, logoutResponse));
93+
});
7594
}
7695

7796
/**
@@ -89,6 +108,16 @@ public void setClock(Clock clock) {
89108
this.clock = clock;
90109
}
91110

111+
private String getSamlStatus(Saml2AuthenticationException exception) {
112+
Saml2Error saml2Error = exception.getSaml2Error();
113+
return switch (saml2Error.getErrorCode()) {
114+
case Saml2ErrorCodes.MISSING_LOGOUT_REQUEST_ENDPOINT, Saml2ErrorCodes.INVALID_BINDING ->
115+
StatusCode.REQUEST_DENIED;
116+
case Saml2ErrorCodes.INVALID_LOGOUT_REQUEST -> StatusCode.REQUESTER;
117+
default -> StatusCode.RESPONDER;
118+
};
119+
}
120+
92121
public static final class LogoutResponseParameters {
93122

94123
private final HttpServletRequest request;

saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2022 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -127,11 +127,11 @@ final class OpenSamlLogoutResponseResolver {
127127
* @return a signed and serialized SAML 2.0 Logout Response
128128
*/
129129
Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication) {
130-
return resolve(request, authentication, (registration, logoutResponse) -> {
130+
return resolve(request, authentication, StatusCode.SUCCESS, (registration, logoutResponse) -> {
131131
});
132132
}
133133

134-
Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication,
134+
Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication, String statusCode,
135135
BiConsumer<RelyingPartyRegistration, LogoutResponse> logoutResponseConsumer) {
136136
LogoutRequest logoutRequest = parse(extractSamlRequest(request));
137137
String registrationId = getRegistrationId(authentication);
@@ -154,7 +154,7 @@ Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentic
154154
issuer.setValue(entityId);
155155
logoutResponse.setIssuer(issuer);
156156
StatusCode code = this.statusCodeBuilder.buildObject();
157-
code.setValue(StatusCode.SUCCESS);
157+
code.setValue(statusCode);
158158
Status status = this.statusBuilder.buildObject();
159159
status.setStatusCode(code);
160160
logoutResponse.setStatus(status);

saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java

Lines changed: 56 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -113,47 +113,84 @@ public Saml2LogoutRequestFilter(RelyingPartyRegistrationResolver relyingPartyReg
113113
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
114114
throws ServletException, IOException {
115115
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
116-
Saml2LogoutRequestValidatorParameters parameters;
117116
try {
118-
parameters = this.logoutRequestResolver.resolve(request, authentication);
117+
Saml2LogoutRequestValidatorParameters parameters = this.logoutRequestResolver.resolve(request,
118+
authentication);
119+
if (parameters == null) {
120+
chain.doFilter(request, response);
121+
return;
122+
}
123+
124+
Saml2LogoutResponse logoutResponse = processLogoutRequest(request, response, authentication, parameters);
125+
sendLogoutResponse(request, response, logoutResponse);
119126
}
120127
catch (Saml2AuthenticationException ex) {
121-
this.logger.trace("Did not process logout request since failed to find requested RelyingPartyRegistration");
122-
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
123-
return;
124-
}
125-
if (parameters == null) {
126-
chain.doFilter(request, response);
127-
return;
128+
Saml2LogoutResponse errorLogoutResponse = this.logoutResponseResolver.resolve(request, authentication, ex);
129+
if (errorLogoutResponse == null) {
130+
this.logger.trace("Returning error since no error logout response could be generated", ex);
131+
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
132+
return;
133+
}
134+
135+
sendLogoutResponse(request, response, errorLogoutResponse);
128136
}
137+
}
138+
139+
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
140+
Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null");
141+
Assert.isInstanceOf(Saml2AssertingPartyLogoutRequestResolver.class, this.logoutRequestResolver,
142+
"saml2LogoutRequestResolver and logoutRequestMatcher cannot both be set. Please set the request matcher in the saml2LogoutRequestResolver itself.");
143+
((Saml2AssertingPartyLogoutRequestResolver) this.logoutRequestResolver)
144+
.setLogoutRequestMatcher(logoutRequestMatcher);
145+
}
146+
147+
/**
148+
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
149+
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
150+
*
151+
* @since 5.8
152+
*/
153+
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
154+
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
155+
this.securityContextHolderStrategy = securityContextHolderStrategy;
156+
}
157+
158+
private Saml2LogoutResponse processLogoutRequest(HttpServletRequest request, HttpServletResponse response,
159+
Authentication authentication, Saml2LogoutRequestValidatorParameters parameters) {
129160
RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration();
130161
if (registration.getSingleLogoutServiceLocation() == null) {
131162
this.logger.trace(
132163
"Did not process logout request since RelyingPartyRegistration has not been configured with a logout request endpoint");
133-
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
134-
return;
164+
throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.MISSING_LOGOUT_REQUEST_ENDPOINT,
165+
"RelyingPartyRegistration has not been configured with a logout request endpoint"));
135166
}
136167

137168
Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request);
138169
if (!registration.getSingleLogoutServiceBindings().contains(saml2MessageBinding)) {
139170
this.logger.trace("Did not process logout request since used incorrect binding");
140-
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
141-
return;
171+
throw new Saml2AuthenticationException(
172+
new Saml2Error(Saml2ErrorCodes.INVALID_BINDING, "Logout request used invalid binding"));
142173
}
143174

144175
Saml2LogoutValidatorResult result = this.logoutRequestValidator.validate(parameters);
145176
if (result.hasErrors()) {
146-
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, result.getErrors().iterator().next().toString());
147177
this.logger.debug(LogMessage.format("Failed to validate LogoutRequest: %s", result.getErrors()));
148-
return;
178+
throw new Saml2AuthenticationException(
179+
new Saml2Error(Saml2ErrorCodes.INVALID_LOGOUT_REQUEST, "Failed to validate the logout request"));
149180
}
181+
150182
this.handler.logout(request, response, authentication);
151183
Saml2LogoutResponse logoutResponse = this.logoutResponseResolver.resolve(request, authentication);
152184
if (logoutResponse == null) {
153-
this.logger.trace("Returning 401 since no logout response generated");
154-
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
155-
return;
185+
this.logger.trace("Returning error since no logout response generated");
186+
throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.FAILED_TO_GENERATE_LOGOUT_RESPONSE,
187+
"Could not generated logout response"));
156188
}
189+
return logoutResponse;
190+
}
191+
192+
private void sendLogoutResponse(HttpServletRequest request, HttpServletResponse response,
193+
Saml2LogoutResponse logoutResponse) throws IOException {
157194
if (logoutResponse.getBinding() == Saml2MessageBinding.REDIRECT) {
158195
doRedirect(request, response, logoutResponse);
159196
}
@@ -162,25 +199,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
162199
}
163200
}
164201

165-
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
166-
Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null");
167-
Assert.isInstanceOf(Saml2AssertingPartyLogoutRequestResolver.class, this.logoutRequestResolver,
168-
"saml2LogoutRequestResolver and logoutRequestMatcher cannot both be set. Please set the request matcher in the saml2LogoutRequestResolver itself.");
169-
((Saml2AssertingPartyLogoutRequestResolver) this.logoutRequestResolver)
170-
.setLogoutRequestMatcher(logoutRequestMatcher);
171-
}
172-
173-
/**
174-
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
175-
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
176-
*
177-
* @since 5.8
178-
*/
179-
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
180-
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
181-
this.securityContextHolderStrategy = securityContextHolderStrategy;
182-
}
183-
184202
private void doRedirect(HttpServletRequest request, HttpServletResponse response,
185203
Saml2LogoutResponse logoutResponse) throws IOException {
186204
String location = logoutResponse.getResponseLocation();

saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseResolver.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@
1919
import jakarta.servlet.http.HttpServletRequest;
2020

2121
import org.springframework.security.core.Authentication;
22+
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
2223
import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse;
2324
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
2425

@@ -44,4 +45,15 @@ public interface Saml2LogoutResponseResolver {
4445
*/
4546
Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication);
4647

48+
/**
49+
* Prepare to create, sign, and serialize a SAML 2.0 Error Logout Response.
50+
* @param request the HTTP request
51+
* @param authentication the current user
52+
* @param authenticationException the thrown exception when the logout request was
53+
* processed
54+
* @return a signed and serialized SAML 2.0 Logout Response
55+
*/
56+
Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication,
57+
Saml2AuthenticationException authenticationException);
58+
4759
}

saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2021 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,17 +17,26 @@
1717
package org.springframework.security.saml2.provider.service.web.authentication.logout;
1818

1919
import java.util.function.Consumer;
20+
import java.util.stream.Stream;
2021

2122
import org.junit.jupiter.api.Test;
23+
import org.junit.jupiter.params.ParameterizedTest;
24+
import org.junit.jupiter.params.provider.Arguments;
25+
import org.junit.jupiter.params.provider.MethodSource;
2226
import org.opensaml.saml.saml2.core.LogoutRequest;
27+
import org.opensaml.saml.saml2.core.StatusCode;
2328

2429
import org.springframework.mock.web.MockHttpServletRequest;
2530
import org.springframework.security.authentication.TestingAuthenticationToken;
2631
import org.springframework.security.core.Authentication;
32+
import org.springframework.security.saml2.core.Saml2Error;
33+
import org.springframework.security.saml2.core.Saml2ErrorCodes;
2734
import org.springframework.security.saml2.core.Saml2ParameterNames;
35+
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
2836
import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects;
2937
import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse;
3038
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
39+
import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding;
3140
import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations;
3241
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver;
3342
import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver.LogoutResponseParameters;
@@ -67,6 +76,26 @@ public void resolveWhenCustomParametersConsumerThenUses() {
6776
verify(parametersConsumer).accept(any());
6877
}
6978

79+
@ParameterizedTest
80+
@MethodSource("provideAuthExceptionAndExpectedSamlStatusCode")
81+
public void resolveWithAuthException(Saml2AuthenticationException exception, String expectedStatusCode) {
82+
OpenSaml4LogoutResponseResolver logoutResponseResolver = new OpenSaml4LogoutResponseResolver(
83+
this.relyingPartyRegistrationResolver);
84+
MockHttpServletRequest request = new MockHttpServletRequest();
85+
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration()
86+
.assertingPartyDetails((party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")
87+
.singleLogoutServiceBinding(Saml2MessageBinding.POST))
88+
.build();
89+
Authentication authentication = new TestingAuthenticationToken("user", "password");
90+
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
91+
request.setParameter(Saml2ParameterNames.SAML_REQUEST,
92+
Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes()));
93+
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
94+
Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication, exception);
95+
assertThat(logoutResponse).isNotNull();
96+
assertThat(new String(Saml2Utils.samlDecode(logoutResponse.getSamlResponse()))).contains(expectedStatusCode);
97+
}
98+
7099
@Test
71100
public void setParametersConsumerWhenNullThenIllegalArgument() {
72101
OpenSaml4LogoutRequestResolver logoutRequestResolver = new OpenSaml4LogoutRequestResolver(
@@ -75,4 +104,23 @@ public void setParametersConsumerWhenNullThenIllegalArgument() {
75104
.isThrownBy(() -> logoutRequestResolver.setParametersConsumer(null));
76105
}
77106

107+
private static Stream<Arguments> provideAuthExceptionAndExpectedSamlStatusCode() {
108+
return Stream.of(
109+
Arguments.of(
110+
new Saml2AuthenticationException(
111+
new Saml2Error(Saml2ErrorCodes.MISSING_LOGOUT_REQUEST_ENDPOINT, "")),
112+
StatusCode.REQUEST_DENIED),
113+
Arguments.of(new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INVALID_BINDING, "")),
114+
StatusCode.REQUEST_DENIED),
115+
Arguments.of(
116+
new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INVALID_LOGOUT_REQUEST, "")),
117+
StatusCode.REQUESTER),
118+
Arguments.of(
119+
new Saml2AuthenticationException(
120+
new Saml2Error(Saml2ErrorCodes.FAILED_TO_GENERATE_LOGOUT_RESPONSE, "")),
121+
StatusCode.RESPONDER)
122+
123+
);
124+
}
125+
78126
}

0 commit comments

Comments
 (0)