1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.util.ArrayList;
22
23 import javax.servlet.ServletContext;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26
27 import org.joda.time.DateTime;
28 import org.joda.time.DateTimeZone;
29 import org.opensaml.Configuration;
30 import org.opensaml.common.SAMLObjectBuilder;
31 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
32 import org.opensaml.common.xml.SAMLConstants;
33 import org.opensaml.saml2.binding.AuthnResponseEndpointSelector;
34 import org.opensaml.saml2.core.AttributeStatement;
35 import org.opensaml.saml2.core.AuthnContext;
36 import org.opensaml.saml2.core.AuthnContextClassRef;
37 import org.opensaml.saml2.core.AuthnContextDeclRef;
38 import org.opensaml.saml2.core.AuthnRequest;
39 import org.opensaml.saml2.core.AuthnStatement;
40 import org.opensaml.saml2.core.NameID;
41 import org.opensaml.saml2.core.NameIDPolicy;
42 import org.opensaml.saml2.core.RequestedAuthnContext;
43 import org.opensaml.saml2.core.Response;
44 import org.opensaml.saml2.core.Statement;
45 import org.opensaml.saml2.core.StatusCode;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.core.SubjectLocality;
48 import org.opensaml.saml2.metadata.AffiliateMember;
49 import org.opensaml.saml2.metadata.AffiliationDescriptor;
50 import org.opensaml.saml2.metadata.AssertionConsumerService;
51 import org.opensaml.saml2.metadata.Endpoint;
52 import org.opensaml.saml2.metadata.EntityDescriptor;
53 import org.opensaml.saml2.metadata.IDPSSODescriptor;
54 import org.opensaml.saml2.metadata.SPSSODescriptor;
55 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
56 import org.opensaml.util.URLBuilder;
57 import org.opensaml.ws.message.decoder.MessageDecodingException;
58 import org.opensaml.ws.transport.http.HTTPInTransport;
59 import org.opensaml.ws.transport.http.HTTPOutTransport;
60 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
61 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
62 import org.opensaml.xml.io.MarshallingException;
63 import org.opensaml.xml.io.Unmarshaller;
64 import org.opensaml.xml.io.UnmarshallingException;
65 import org.opensaml.xml.security.SecurityException;
66 import org.opensaml.xml.util.DatatypeHelper;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Element;
70
71 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
72 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
73 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
74 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
75 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager;
76 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
77 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
78 import edu.internet2.middleware.shibboleth.idp.authn.PassiveAuthenticationException;
79 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
80 import edu.internet2.middleware.shibboleth.idp.session.Session;
81 import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
82
83
84 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
85
86
87 private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
88
89
90 private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
91
92
93 private SAMLObjectBuilder<AuthnContext> authnContextBuilder;
94
95
96 private SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
97
98
99 private SAMLObjectBuilder<AuthnContextDeclRef> authnContextDeclRefBuilder;
100
101
102 private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
103
104
105 private SAMLObjectBuilder<Endpoint> endpointBuilder;
106
107
108 private String authenticationManagerPath;
109
110
111
112
113
114
115 @SuppressWarnings("unchecked")
116 public SSOProfileHandler(String authnManagerPath) {
117 super();
118
119 if (DatatypeHelper.isEmpty(authnManagerPath)) {
120 throw new IllegalArgumentException("Authentication manager path may not be null");
121 }
122 if (authnManagerPath.startsWith("/")) {
123 authenticationManagerPath = authnManagerPath;
124 } else {
125 authenticationManagerPath = "/" + authnManagerPath;
126 }
127
128 authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
129 AuthnStatement.DEFAULT_ELEMENT_NAME);
130 authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) getBuilderFactory().getBuilder(
131 AuthnContext.DEFAULT_ELEMENT_NAME);
132 authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) getBuilderFactory().getBuilder(
133 AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
134 authnContextDeclRefBuilder = (SAMLObjectBuilder<AuthnContextDeclRef>) getBuilderFactory().getBuilder(
135 AuthnContextDeclRef.DEFAULT_ELEMENT_NAME);
136 subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
137 SubjectLocality.DEFAULT_ELEMENT_NAME);
138 endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
139 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
140 }
141
142
143 public String getProfileId() {
144 return SSOConfiguration.PROFILE_ID;
145 }
146
147
148 public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
149 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
150 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
151 ServletContext servletContext = httpRequest.getSession().getServletContext();
152
153 Saml2LoginContext loginContext = (Saml2LoginContext) HttpServletHelper.getLoginContext(getStorageService(),
154 servletContext, httpRequest);
155 if (loginContext == null) {
156 log.debug("Incoming request does not contain a login context, processing as first leg of request");
157 performAuthentication(inTransport, outTransport);
158 }else if(!loginContext.isPrincipalAuthenticated()){
159 log.debug("Incoming request contained a login context but principal was not authenticated, processing as first leg of request");
160 performAuthentication(inTransport, outTransport);
161 } else {
162 log.debug("Incoming request contains a login context, processing as second leg of request");
163 HttpServletHelper.unbindLoginContext(getStorageService(), servletContext, httpRequest, httpResponse);
164 completeAuthenticationRequest(loginContext, inTransport, outTransport);
165 }
166 }
167
168
169
170
171
172
173
174
175
176
177
178 protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
179 throws ProfileException {
180 HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
181 HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
182
183 SSORequestContext requestContext = new SSORequestContext();
184
185 try {
186 decodeRequest(requestContext, inTransport, outTransport);
187
188 String relyingPartyId = requestContext.getInboundMessageIssuer();
189 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
190 ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(getProfileId());
191 if (ssoConfig == null) {
192 String msg = "SAML 2 SSO profile is not configured for relying party "
193 + requestContext.getInboundMessageIssuer();
194 log.warn(msg);
195 throw new ProfileException(msg);
196 }
197
198 log.debug("Creating login context and transferring control to authentication engine");
199 Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, requestContext.getRelayState(),
200 requestContext.getInboundSAMLMessage());
201 loginContext.setAuthenticationEngineURL(authenticationManagerPath);
202 loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
203 loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
204
205 HttpServletHelper.bindLoginContext(loginContext, getStorageService(), httpRequest.getSession()
206 .getServletContext(), httpRequest, httpResponse);
207
208 URLBuilder urlBuilder = HttpServletHelper.getServletContextUrl(httpRequest);
209 urlBuilder.setPath(urlBuilder.getPath() + authenticationManagerPath);
210 String authnEngineUrl = urlBuilder.buildURL();
211 log.debug("Redirecting user to authentication engine at {}", authnEngineUrl);
212 httpResponse.sendRedirect(authnEngineUrl);
213 } catch (MarshallingException e) {
214 log.error("Unable to marshall authentication request context");
215 throw new ProfileException("Unable to marshall authentication request context", e);
216 } catch (IOException ex) {
217 log.error("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
218 throw new ProfileException("Error forwarding SAML 2 AuthnRequest to AuthenticationManager", ex);
219 }
220 }
221
222
223
224
225
226
227
228
229
230
231
232 protected void completeAuthenticationRequest(Saml2LoginContext loginContext, HTTPInTransport inTransport,
233 HTTPOutTransport outTransport) throws ProfileException {
234 SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
235
236 Response samlResponse;
237 try {
238 checkSamlVersion(requestContext);
239 checkNameIDPolicy(requestContext);
240
241 if (loginContext.getAuthenticationFailure() != null) {
242 if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
243 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
244 null));
245 } else {
246 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
247 null));
248 }
249 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
250 }
251
252 if (requestContext.getSubjectNameIdentifier() != null) {
253 log
254 .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
255 resolvePrincipal(requestContext);
256 String requestedPrincipalName = requestContext.getPrincipalName();
257 if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
258 log
259 .warn(
260 "Authentication request identified principal {} but authentication mechanism identified principal {}",
261 requestedPrincipalName, loginContext.getPrincipalName());
262 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
263 null));
264 throw new ProfileException("User failed authentication");
265 }
266 }
267
268 resolveAttributes(requestContext);
269
270 ArrayList<Statement> statements = new ArrayList<Statement>();
271 statements.add(buildAuthnStatement(requestContext));
272 if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
273 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
274 if (attributeStatement != null) {
275 requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
276 statements.add(attributeStatement);
277 }
278 }
279
280 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
281 } catch (ProfileException e) {
282 samlResponse = buildErrorResponse(requestContext);
283 }
284
285 requestContext.setOutboundSAMLMessage(samlResponse);
286 requestContext.setOutboundSAMLMessageId(samlResponse.getID());
287 requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
288 encodeResponse(requestContext);
289 writeAuditLogEntry(requestContext);
290 }
291
292
293
294
295
296
297
298
299
300
301 protected void decodeRequest(SSORequestContext requestContext, HTTPInTransport inTransport,
302 HTTPOutTransport outTransport) throws ProfileException {
303 if (log.isDebugEnabled()) {
304 log.debug("Decoding message with decoder binding '{}'", getInboundMessageDecoder(requestContext)
305 .getBindingURI());
306 }
307
308 requestContext.setCommunicationProfileId(getProfileId());
309
310 requestContext.setMetadataProvider(getMetadataProvider());
311 requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
312
313 requestContext.setCommunicationProfileId(getProfileId());
314 requestContext.setInboundMessageTransport(inTransport);
315 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
316 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
317
318 requestContext.setOutboundMessageTransport(outTransport);
319 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
320
321 try {
322 SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
323 requestContext.setMessageDecoder(decoder);
324 decoder.decode(requestContext);
325 log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessageIssuer());
326
327 if (!(requestContext.getInboundSAMLMessage() instanceof AuthnRequest)) {
328 log.warn("Incomming message was not a AuthnRequest, it was a '{}'", requestContext
329 .getInboundSAMLMessage().getClass().getName());
330 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
331 "Invalid SAML AuthnRequest message."));
332 throw new ProfileException("Invalid SAML AuthnRequest message.");
333 }
334 } catch (MessageDecodingException e) {
335 String msg = "Error decoding authentication request message";
336 log.warn(msg, e);
337 throw new ProfileException(msg, e);
338 } catch (SecurityException e) {
339 String msg = "Message did not meet security requirements";
340 log.warn(msg, e);
341 throw new ProfileException(msg, e);
342 }
343 }
344
345
346
347
348
349
350
351
352
353
354 protected void checkNameIDPolicy(SSORequestContext requestContext) throws ProfileException {
355 AuthnRequest request = requestContext.getInboundSAMLMessage();
356
357 NameIDPolicy nameIdPolcy = request.getNameIDPolicy();
358 if (nameIdPolcy == null) {
359 return;
360 }
361
362 String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolcy.getSPNameQualifier());
363 if (spNameQualifier == null) {
364 return;
365 }
366
367 log.debug("Checking if message issuer is a member of affiliation '{}'", spNameQualifier);
368 try {
369 EntityDescriptor affiliation = getMetadataProvider().getEntityDescriptor(spNameQualifier);
370 if (affiliation != null) {
371 AffiliationDescriptor affiliationDescriptor = affiliation.getAffiliationDescriptor();
372 if (affiliationDescriptor != null && affiliationDescriptor.getMembers() != null) {
373 for (AffiliateMember member : affiliationDescriptor.getMembers()) {
374 if (DatatypeHelper.safeEquals(member.getID(), requestContext.getInboundMessageIssuer())) {
375 return;
376 }
377 }
378 }
379 }
380
381 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
382 "Invalid SPNameQualifier for this request"));
383 throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
384 + "' is not a member of the affiliation " + spNameQualifier);
385 } catch (MetadataProviderException e) {
386 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Internal service error"));
387 log.error("Error looking up metadata for affiliation", e);
388 throw new ProfileException("Relying party '" + requestContext.getInboundMessageIssuer()
389 + "' is not a member of the affiliation " + spNameQualifier);
390 }
391 }
392
393
394
395
396
397
398
399
400
401
402
403
404 protected SSORequestContext buildRequestContext(Saml2LoginContext loginContext, HTTPInTransport in,
405 HTTPOutTransport out) throws ProfileException {
406 SSORequestContext requestContext = new SSORequestContext();
407 requestContext.setCommunicationProfileId(getProfileId());
408
409 requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
410
411 requestContext.setLoginContext(loginContext);
412
413 requestContext.setInboundMessageTransport(in);
414 requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
415
416 requestContext.setOutboundMessageTransport(out);
417 requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
418
419 requestContext.setMetadataProvider(getMetadataProvider());
420
421 String relyingPartyId = loginContext.getRelyingPartyId();
422 requestContext.setPeerEntityId(relyingPartyId);
423 requestContext.setInboundMessageIssuer(relyingPartyId);
424
425 populateRequestContext(requestContext);
426
427 return requestContext;
428 }
429
430
431 protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
432 throws ProfileException {
433 super.populateRelyingPartyInformation(requestContext);
434
435 EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
436 if (relyingPartyMetadata != null) {
437 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
438 requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
439 }
440 }
441
442
443 protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
444 throws ProfileException {
445 super.populateAssertingPartyInformation(requestContext);
446
447 EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
448 if (localEntityDescriptor != null) {
449 requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
450 requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
451 .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
452 }
453 }
454
455
456
457
458
459
460
461
462
463
464
465
466
467 protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
468 SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
469 try {
470 Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
471 requestContext.setRelayState(loginContext.getRelayState());
472
473 AuthnRequest authnRequest = deserializeRequest(loginContext.getAuthenticationRequest());
474 requestContext.setInboundMessage(authnRequest);
475 requestContext.setInboundSAMLMessage(authnRequest);
476 requestContext.setInboundSAMLMessageId(authnRequest.getID());
477
478 Subject authnSubject = authnRequest.getSubject();
479 if (authnSubject != null) {
480 requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
481 }
482 } catch (UnmarshallingException e) {
483 log.error("Unable to unmarshall authentication request context");
484 ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
485 "Error recovering request state"));
486 throw new ProfileException("Error recovering request state", e);
487 }
488 }
489
490
491
492
493
494
495
496
497 protected AuthnStatement buildAuthnStatement(SSORequestContext requestContext) {
498 Saml2LoginContext loginContext = requestContext.getLoginContext();
499
500 AuthnContext authnContext = buildAuthnContext(requestContext);
501
502 AuthnStatement statement = authnStatementBuilder.buildObject();
503 statement.setAuthnContext(authnContext);
504 statement.setAuthnInstant(loginContext.getAuthenticationInstant());
505
506 Session session = getUserSession(requestContext.getInboundMessageTransport());
507 if (session != null) {
508 statement.setSessionIndex(session.getSessionID());
509 }
510
511 long maxSPSessionLifetime = requestContext.getProfileConfiguration().getMaximumSPSessionLifetime();
512 if (maxSPSessionLifetime > 0) {
513 DateTime lifetime = new DateTime(DateTimeZone.UTC).plus(maxSPSessionLifetime);
514 log.debug("Explicitly setting SP session expiration time to '{}'", lifetime.toString());
515 statement.setSessionNotOnOrAfter(lifetime);
516 }
517
518 statement.setSubjectLocality(buildSubjectLocality(requestContext));
519
520 return statement;
521 }
522
523
524
525
526
527
528
529
530 protected AuthnContext buildAuthnContext(SSORequestContext requestContext) {
531 AuthnContext authnContext = authnContextBuilder.buildObject();
532
533 Saml2LoginContext loginContext = requestContext.getLoginContext();
534 AuthnRequest authnRequest = requestContext.getInboundSAMLMessage();
535 RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
536 if (requestedAuthnContext != null) {
537 if (requestedAuthnContext.getAuthnContextClassRefs() != null) {
538 for (AuthnContextClassRef classRef : requestedAuthnContext.getAuthnContextClassRefs()) {
539 if (classRef.getAuthnContextClassRef().equals(loginContext.getAuthenticationMethod())) {
540 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
541 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
542 authnContext.setAuthnContextClassRef(ref);
543 }
544 }
545 } else if (requestedAuthnContext.getAuthnContextDeclRefs() != null) {
546 for (AuthnContextDeclRef declRef : requestedAuthnContext.getAuthnContextDeclRefs()) {
547 if (declRef.getAuthnContextDeclRef().equals(loginContext.getAuthenticationMethod())) {
548 AuthnContextDeclRef ref = authnContextDeclRefBuilder.buildObject();
549 ref.setAuthnContextDeclRef(loginContext.getAuthenticationMethod());
550 authnContext.setAuthnContextDeclRef(ref);
551 }
552 }
553 }
554 }
555
556 if (authnContext.getAuthnContextClassRef() == null || authnContext.getAuthnContextDeclRef() == null) {
557 AuthnContextClassRef ref = authnContextClassRefBuilder.buildObject();
558 ref.setAuthnContextClassRef(loginContext.getAuthenticationMethod());
559 authnContext.setAuthnContextClassRef(ref);
560 }
561
562 return authnContext;
563 }
564
565
566
567
568
569
570
571
572 protected SubjectLocality buildSubjectLocality(SSORequestContext requestContext) {
573 HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
574 SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
575 subjectLocality.setAddress(transport.getPeerAddress());
576
577 return subjectLocality;
578 }
579
580
581 protected String getRequiredNameIDFormat(BaseSAMLProfileRequestContext requestContext) {
582 String requiredNameFormat = null;
583 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
584 NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
585 if (nameIdPolicy != null) {
586 requiredNameFormat = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getFormat());
587
588 if (requiredNameFormat != null
589 && (NameID.ENCRYPTED.equals(requiredNameFormat) || NameID.UNSPECIFIED.equals(requiredNameFormat))) {
590 requiredNameFormat = null;
591 }
592 }
593
594 return requiredNameFormat;
595 }
596
597
598 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
599 NameID nameId = super.buildNameId(requestContext);
600 if (nameId != null) {
601 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
602 NameIDPolicy nameIdPolicy = authnRequest.getNameIDPolicy();
603 if (nameIdPolicy != null) {
604 String spNameQualifier = DatatypeHelper.safeTrimOrNullString(nameIdPolicy.getSPNameQualifier());
605 if (spNameQualifier != null) {
606 nameId.setSPNameQualifier(spNameQualifier);
607 } else {
608 nameId.setSPNameQualifier(requestContext.getInboundMessageIssuer());
609 }
610 }
611 }
612
613 return nameId;
614 }
615
616
617
618
619
620
621
622
623 protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
624 AuthnRequest authnRequest = ((SSORequestContext) requestContext).getInboundSAMLMessage();
625
626 Endpoint endpoint = null;
627 if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
628 if (authnRequest.getAssertionConsumerServiceURL() != null) {
629 endpoint = endpointBuilder.buildObject();
630 endpoint.setLocation(authnRequest.getAssertionConsumerServiceURL());
631 if (authnRequest.getProtocolBinding() != null) {
632 endpoint.setBinding(authnRequest.getProtocolBinding());
633 } else {
634 endpoint.setBinding(getSupportedOutboundBindings().get(0));
635 }
636 log
637 .warn(
638 "Generating endpoint for anonymous relying party self-identified as '{}', ACS url '{}' and binding '{}'",
639 new Object[] { requestContext.getInboundMessageIssuer(), endpoint.getLocation(),
640 endpoint.getBinding(), });
641 } else {
642 log.warn("Unable to generate endpoint for anonymous party. No ACS url provided.");
643 }
644 } else {
645 AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
646 endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
647 endpointSelector.setMetadataProvider(getMetadataProvider());
648 endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
649 endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
650 endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
651 endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
652 endpoint = endpointSelector.selectEndpoint();
653 }
654
655 return endpoint;
656 }
657
658
659
660
661
662
663
664
665
666
667 protected AuthnRequest deserializeRequest(String request) throws UnmarshallingException {
668 try {
669 Element requestElem = getParserPool().parse(new StringReader(request)).getDocumentElement();
670 Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(requestElem);
671 return (AuthnRequest) unmarshaller.unmarshall(requestElem);
672 } catch (Exception e) {
673 throw new UnmarshallingException("Unable to read serialized authentication request");
674 }
675 }
676
677
678 protected class SSORequestContext extends BaseSAML2ProfileRequestContext<AuthnRequest, Response, SSOConfiguration> {
679
680
681 private Saml2LoginContext loginContext;
682
683
684
685
686
687
688 public Saml2LoginContext getLoginContext() {
689 return loginContext;
690 }
691
692
693
694
695
696
697 public void setLoginContext(Saml2LoginContext context) {
698 loginContext = context;
699 }
700 }
701 }