This repository has been archived by the owner on Nov 29, 2022. It is now read-only.
/
SAMLLogoutProcessingFilter.java
319 lines (273 loc) · 12.7 KB
/
SAMLLogoutProcessingFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/* Copyright 2009 Vladimir Schäfer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.saml;
import org.opensaml.common.SAMLException;
import org.opensaml.common.binding.decoding.URIComparator;
import org.opensaml.saml2.core.LogoutRequest;
import org.opensaml.saml2.core.LogoutResponse;
import org.opensaml.saml2.core.StatusCode;
import org.opensaml.saml2.metadata.provider.MetadataProviderException;
import org.opensaml.ws.message.decoder.MessageDecodingException;
import org.opensaml.ws.transport.InTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.saml.context.SAMLContextProvider;
import org.springframework.security.saml.context.SAMLMessageContext;
import org.springframework.security.saml.log.SAMLLogger;
import org.springframework.security.saml.processor.SAMLProcessor;
import org.springframework.security.saml.util.DefaultURLComparator;
import org.springframework.security.saml.util.SAMLUtil;
import org.springframework.security.saml.websso.SingleLogoutProfile;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.Assert;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Filter processes arriving SAML Single Logout messages by delegating to the LogoutProfile.
*
* @author Vladimir Schäfer
*/
public class SAMLLogoutProcessingFilter extends LogoutFilter {
protected SAMLProcessor processor;
protected SingleLogoutProfile logoutProfile;
protected SAMLLogger samlLogger;
protected SAMLContextProvider contextProvider;
protected URIComparator uriComparator = new DefaultURLComparator();
/**
* Class logger.
*/
protected static final Logger log = LoggerFactory.getLogger(SAMLLogoutProcessingFilter.class);
/**
* Default processing URL.
*/
public static final String FILTER_URL = "/saml/SingleLogout";
/**
* Logout handlers.
*/
private final List<LogoutHandler> handlers;
private String filterProcessesUrl;
/**
* Constructor defines URL to redirect to after successful logout and handlers.
*
* @param logoutSuccessUrl user will be redirected to the url after successful logout
* @param handlers handlers to invoke after logout
*/
public SAMLLogoutProcessingFilter(String logoutSuccessUrl, LogoutHandler... handlers) {
super(logoutSuccessUrl, handlers);
this.setFilterProcessesUrl(FILTER_URL);
this.handlers = Arrays.asList(handlers);
}
/**
* Constructor uses custom implementation for determining URL to redirect after successful logout.
*
* @param logoutSuccessHandler custom implementation of the logout logic
* @param handlers handlers to invoke after logout
*/
public SAMLLogoutProcessingFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
super(logoutSuccessHandler, handlers);
this.handlers = Arrays.asList(handlers);
this.setFilterProcessesUrl(FILTER_URL);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
processLogout((HttpServletRequest) req, (HttpServletResponse) res, chain);
}
/**
* Filter loads SAML message from the request object and processes it. In case the message is of LogoutResponse
* type it is validated and user is redirected to the success page. In case the message is invalid error
* is logged and user is redirected to the success page anyway.
* <p>
* In case the LogoutRequest message is received it will be verified and local session will be destroyed.
*
* @param request http request
* @param response http response
* @param chain chain
* @throws IOException error
* @throws ServletException error
*/
public void processLogout(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (requiresLogout(request, response)) {
SAMLMessageContext context;
try {
log.debug("Processing SAML logout message");
context = contextProvider.getLocalEntity(request, response);
context.setCommunicationProfileId(getProfileName());
processor.retrieveMessage(context);
context.setLocalEntityEndpoint(SAMLUtil.getEndpoint(context.getLocalEntityRoleMetadata().getEndpoints(), context.getInboundSAMLBinding(), context.getInboundMessageTransport(), uriComparator));
} catch (SAMLException e) {
log.debug("Incoming SAML message is invalid", e);
throw new ServletException("Incoming SAML message is invalid", e);
} catch (MetadataProviderException e) {
log.debug("Error determining metadata contracts", e);
throw new ServletException("Error determining metadata contracts", e);
} catch (MessageDecodingException e) {
log.debug("Error decoding incoming SAML message", e);
throw new ServletException("Error decoding incoming SAML message", e);
} catch (org.opensaml.xml.security.SecurityException e) {
log.debug("Incoming SAML message failed security validation", e);
throw new ServletException("Incoming SAML message failed security validation", e);
}
if (context.getInboundSAMLMessage() instanceof LogoutResponse) {
try {
logoutProfile.processLogoutResponse(context);
log.debug("Performing local logout after receiving logout response from {}", context.getPeerEntityId());
super.doFilter(request, response, chain);
samlLogger.log(SAMLConstants.LOGOUT_RESPONSE, SAMLConstants.SUCCESS, context);
} catch (Exception e) {
log.debug("Received logout response is invalid", e);
samlLogger.log(SAMLConstants.LOGOUT_RESPONSE, SAMLConstants.FAILURE, context, e);
}
} else if (context.getInboundSAMLMessage() instanceof LogoutRequest) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
SAMLCredential credential = null;
if (auth != null) {
credential = (SAMLCredential) auth.getCredentials();
}
try {
boolean doLogout;
try {
doLogout = logoutProfile.processLogoutRequest(context, credential);
} catch (SAMLStatusException e) {
log.debug("Received logout request is invalid, responding with error", e);
logoutProfile.sendLogoutResponse(context, e.getStatusCode(), e.getStatusMessage());
samlLogger.log(SAMLConstants.LOGOUT_REQUEST, SAMLConstants.FAILURE, context, e);
return;
}
if (doLogout) {
log.debug("Performing local logout after receiving logout request from {}", context.getPeerEntityId());
for (LogoutHandler handler : handlers) {
handler.logout(request, response, auth);
}
}
logoutProfile.sendLogoutResponse(context, StatusCode.SUCCESS_URI, null);
samlLogger.log(SAMLConstants.LOGOUT_REQUEST, SAMLConstants.SUCCESS, context);
} catch (Exception e) {
log.debug("Error processing logout request", e);
samlLogger.log(SAMLConstants.LOGOUT_REQUEST, SAMLConstants.FAILURE, context, e);
throw new ServletException("Error processing logout request", e);
}
}
} else {
chain.doFilter(request, response);
}
}
/**
* Name of the profile processed by this class.
*
* @return profile name
*/
protected String getProfileName() {
return SAMLConstants.SAML2_SLO_PROFILE_URI;
}
/**
* The filter will be used in case the URL of the request contains the DEFAULT_FILTER_URL.
*
* @param request request used to determine whether to enable this filter
* @return true if this filter should be used
*/
@Override
protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
return SAMLUtil.processFilter(getFilterProcessesUrl(), request);
}
/**
* Object capable of parse SAML messages from requests, must be set.
*
* @param processor processor
*/
@Autowired
public void setSAMLProcessor(SAMLProcessor processor) {
Assert.notNull(processor, "SAML Processor can't be null");
this.processor = processor;
}
/**
* Profile for consumption of processed messages, must be set.
*
* @param logoutProfile profile
*/
@Autowired
public void setLogoutProfile(SingleLogoutProfile logoutProfile) {
Assert.notNull(logoutProfile, "SingleLogoutProfile can't be null");
this.logoutProfile = logoutProfile;
}
/**
* Logger for SAML events, must be set.
*
* @param samlLogger logger
*/
@Autowired
public void setSamlLogger(SAMLLogger samlLogger) {
Assert.notNull(samlLogger, "SAML logger can't be null");
this.samlLogger = samlLogger;
}
/**
* Sets entity responsible for populating local entity context data. Must be set.
*
* @param contextProvider provider implementation
*/
@Autowired
public void setContextProvider(SAMLContextProvider contextProvider) {
Assert.notNull(contextProvider, "Context provider can't be null");
this.contextProvider = contextProvider;
}
/**
* Sets URI comparator used to get local entity endpoint
* @param uriComparator URI comparator
* @see SAMLUtil#getEndpoint(List, String, InTransport, URIComparator)
*/
@Autowired(required = false)
public void setUriComparator(URIComparator uriComparator) {
Assert.notNull(uriComparator, "URI comparator can't be null");
this.uriComparator = uriComparator;
}
/**
* Verifies that required entities were autowired or set.
*/
@Override
public void afterPropertiesSet() throws ServletException {
super.afterPropertiesSet();
Assert.notNull(processor, "SAMLProcessor must be set");
Assert.notNull(contextProvider, "Context provider must be set");
Assert.notNull(logoutProfile, "Logout profile must be set");
Assert.notNull(samlLogger, "SAML Logger must be set");
}
/**
* Sets the URL used to determine if this Filter is invoked
* @param filterProcessesUrl the URL used to determine if this Filter is invoked
*/
@Override
public void setFilterProcessesUrl(String filterProcessesUrl) {
this.filterProcessesUrl = filterProcessesUrl;
super.setFilterProcessesUrl(filterProcessesUrl);
}
/**
* Gets the URL used to determine if this Filter is invoked
* @return the URL used to determine if this Fitler is invoked
*/
public String getFilterProcessesUrl() {
return filterProcessesUrl;
}
}