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