assertion.getAttributeStatements().add(attributeStatement);
Assertion assertion = response.getAssertions().get(0); DateTime until = new DateTime().plusHours(1); assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setRecipient(spEndpoint); assertion.getConditions().getAudienceRestrictions().get(0).getAudiences().get(0).setAudienceURI(audienceEntityID); assertion.getIssuer().setValue(issuerEntityId); assertion.getSubject().getNameID().setValue(username); assertion.getSubject().getNameID().setFormat(format); assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setInResponseTo(null); assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().setNotOnOrAfter(until); assertion.getConditions().setNotOnOrAfter(until); SamlConfig config = new SamlConfig(); config.addAndActivateKey("active-key", new SamlKey(privateKey, keyPassword, certificate)); signature.setSigningCredential(defaultCredential); SecurityHelper.prepareSignatureParams(signature, defaultCredential, null, null); assertion.setSignature(signature); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(assertion); marshaller.marshall(assertion);
public MultiValueMap<String, String> retrieveUserAttributes(SamlIdentityProviderDefinition definition, SAMLCredential credential) { logger.debug(String.format("Retrieving SAML user attributes [zone:%s, origin:%s]", definition.getZoneId(), definition.getIdpEntityAlias())); MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>(); if (definition != null && definition.getAttributeMappings() != null) { for (Entry<String, Object> attributeMapping : definition.getAttributeMappings().entrySet()) { if (attributeMapping.getValue() instanceof String) { if (credential.getAttribute((String)attributeMapping.getValue()) != null) { String key = attributeMapping.getKey(); for (XMLObject xmlObject : credential.getAttribute((String) attributeMapping.getValue()).getAttributeValues()) { String value = getStringValue(key, definition, xmlObject); if (value!=null) { userAttributes.add(key, value); } } } } } } if (credential.getAuthenticationAssertion() != null && credential.getAuthenticationAssertion().getAuthnStatements() != null) { for (AuthnStatement statement : credential.getAuthenticationAssertion().getAuthnStatements()) { if (statement.getAuthnContext() != null && statement.getAuthnContext().getAuthnContextClassRef() != null) { userAttributes.add(AUTHENTICATION_CONTEXT_CLASS_REFERENCE, statement.getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef()); } } } return userAttributes; }
private Assertion buildAssertion(Authentication authentication, AuthnRequest authnRequest, IdpWebSSOProfileOptions options, String audienceURI, String issuerEntityId) throws SAMLException{ @SuppressWarnings("unchecked") SAMLObjectBuilder<Assertion> assertionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory .getBuilder(Assertion.DEFAULT_ELEMENT_NAME); Assertion assertion = assertionBuilder.buildObject(); assertion.setID(generateID()); assertion.setIssueInstant(new DateTime()); assertion.setVersion(SAMLVersion.VERSION_20); assertion.setIssuer(getIssuer(issuerEntityId)); buildAssertionAuthnStatement(assertion); buildAssertionConditions(assertion, options.getAssertionTimeToLiveSeconds(), audienceURI); buildAssertionSubject(assertion, authnRequest, options.getAssertionTimeToLiveSeconds(), (UaaPrincipal) authentication.getPrincipal()); buildAttributeStatement(assertion, authentication, audienceURI); return assertion; }
@Test public void testBuildResponseWithSignedAssertion() throws MessageEncodingException, SAMLException, MetadataProviderException, SecurityException, MarshallingException, SignatureException { String authenticationId = UUID.randomUUID().toString(); Authentication authentication = samlTestUtils.mockUaaAuthentication(authenticationId); SAMLMessageContext context = samlTestUtils.mockSamlMessageContext(); IdpWebSSOProfileOptions options = new IdpWebSSOProfileOptions(); options.setAssertionsSigned(true); profile.buildResponse(authentication, context, options); AuthnRequest request = (AuthnRequest) context.getInboundSAMLMessage(); Response response = (Response) context.getOutboundSAMLMessage(); Assertion assertion = response.getAssertions().get(0); Subject subject = assertion.getSubject(); assertEquals("marissa", subject.getNameID().getValue()); SubjectConfirmation subjectConfirmation = subject.getSubjectConfirmations().get(0); SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData(); assertEquals(request.getID(), subjectConfirmationData.getInResponseTo()); verifyAssertionAttributes(authenticationId, assertion); assertNotNull(assertion.getSignature()); }
@Override public Assertion build() { AssertionBuilder assertionBuilder = (AssertionBuilder) xmlObjectBuilderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME); Assertion assertion = assertionBuilder.buildObject(); assertion.setID(id); assertion.setIssueInstant(issueInstant); assertion.setVersion(SAMLVersion.VERSION_20); assertion.setIssuer(issuer); assertion.setSubject(subject); assertion.setConditions(conditions); if(signature !=null){ assertion.setSignature(signature); } if(authnStatements.size() > 0){ for (AuthnStatement authnStatement : authnStatements) { assertion.getAuthnStatements().add(authnStatement); } } if(attributeStatements.size() > 0){ for (AttributeStatement attributeStatement : attributeStatements) { assertion.getAttributeStatements().add(attributeStatement); } } return assertion; }
params.getAuthenStateBean() ); saml2.getAuthnStatements().addAll(authnStatements); params.getAttrBean() ); saml2.getAttributeStatements().addAll(attributeStatements); params.getAuthzBean() ); saml2.getAuthzDecisionStatements().addAll(authDecisionStatements); saml2.setIssuer(samlIssuer); saml2.setSubject(subject); } catch (org.opensaml.xml.security.SecurityException ex) { throw new Exception(
private void verifyAssertion(Assertion assertion, AuthnRequest request, BasicSAMLMessageContext context) throws SAMLException, org.opensaml.xml.security.SecurityException, ValidationException, Exception { // Verify assertion time skew if (!isDateTimeSkewValid(MAX_ASSERTION_TIME, assertion.getIssueInstant())) { System.out.println("Authentication statement is too old to be used"+assertion.getIssueInstant()); throw new Exception("Users authentication credential is too old to be used"); } // Verify validity of assertion // Advice is ignored, core 574 verifyIssuer(assertion.getIssuer(), context); verifyAssertionSignature(assertion.getSignature(), context); verifySubject(assertion.getSubject(), request, context); // Assertion with authentication statement must contain audience restriction if (assertion.getAuthnStatements().size() > 0) { verifyAssertionConditions(assertion.getConditions(), context, true); for (AuthnStatement statement : assertion.getAuthnStatements()) { verifyAuthenticationStatement(statement, context); } } else { verifyAssertionConditions(assertion.getConditions(), context, false); } } /**
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { Assertion assertion = (Assertion) samlObject; if (attribute.getLocalName().equals(Assertion.VERSION_ATTRIB_NAME)) { assertion.setVersion(SAMLVersion.valueOf(attribute.getValue())); } else if (attribute.getLocalName().equals(Assertion.ISSUE_INSTANT_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(Assertion.ID_ATTRIB_NAME)) { assertion.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else { super.processAttribute(samlObject, attribute); } } }
DateTime currentTime = new DateTime(); Assertion assertion = assertionBuilder.buildObject(); assertion.setVersion(org.opensaml.common.SAMLVersion.VERSION_20); assertion.setIssuer(createIssuer()); assertion.setIssueInstant(currentTime); assertion.getStatements().add(xacmlAuthzDecisionStatement); ResponseBuilder builder = (ResponseBuilder) org.opensaml.xml.Configuration.getBuilderFactory() .getBuilder(Response.DEFAULT_ELEMENT_NAME);
/** * Checks that the Subject element is present when required. * * @param assertion * @throws ValidationException */ protected void validateSubject(Assertion assertion) throws ValidationException { if ((assertion.getStatements() == null || assertion.getStatements().size() == 0) && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().size() == 0) && (assertion.getAttributeStatements() == null || assertion.getAttributeStatements().size() == 0) && (assertion.getAuthzDecisionStatements() == null || assertion.getAuthzDecisionStatements().size() == 0) && assertion.getSubject() == null) { throw new ValidationException("Subject is required when Statements are absent"); } if (assertion.getAuthnStatements().size() > 0 && assertion.getSubject() == null) { throw new ValidationException("Assertions containing AuthnStatements require a Subject"); } if (assertion.getAuthzDecisionStatements().size() > 0 && assertion.getSubject() == null) { throw new ValidationException("Assertions containing AuthzDecisionStatements require a Subject"); } if (assertion.getAttributeStatements().size() > 0 && assertion.getSubject() == null) { throw new ValidationException("Assertions containing AttributeStatements require a Subject"); } } }
private Map<String, Object> getUserAttributes(ResponseImpl samlResponse) { Map<String, Object> userAttributes = new HashMap<>(); // Add 'Subject' Assertion assertion = samlResponse.getAssertions().get(0); userAttributes.put(SAMLConstants.SAML2_ASSERTION_SUBJECT, assertion.getSubject().getNameID().getValue()); // Add other user attributes. List<AttributeStatement> attributeStatements = assertion.getAttributeStatements(); if (attributeStatements != null) { for (AttributeStatement attributeStatement : attributeStatements) { List<Attribute> attributes = attributeStatement.getAttributes(); for (Attribute attribute : attributes) { if (attribute.getAttributeValues().size() > 1) { List<XMLObject> attributeValues = attribute.getAttributeValues(); List<String> attributeValuesList = new ArrayList<String>(); for (XMLObject attributeValue : attributeValues) { attributeValuesList.add(attributeValue.getDOM().getTextContent()); } userAttributes.put(attribute.getName(), attributeValuesList); } else { userAttributes.put(attribute.getName(), attribute.getAttributeValues().get(0).getDOM().getTextContent()); } } } } return userAttributes; }
@Test public void testBuildResponseForSamlRequestWithEmailAddressNameID() throws MessageEncodingException, SAMLException, MetadataProviderException, SecurityException, MarshallingException, SignatureException { String authenticationId = UUID.randomUUID().toString(); Authentication authentication = samlTestUtils.mockUaaAuthentication(authenticationId); SAMLMessageContext context = samlTestUtils.mockSamlMessageContext( samlTestUtils.mockAuthnRequest(NameIDType.EMAIL)); IdpWebSSOProfileOptions options = new IdpWebSSOProfileOptions(); options.setAssertionsSigned(false); profile.buildResponse(authentication, context, options); AuthnRequest request = (AuthnRequest) context.getInboundSAMLMessage(); Response response = (Response) context.getOutboundSAMLMessage(); Assertion assertion = response.getAssertions().get(0); Subject subject = assertion.getSubject(); assertEquals("marissa@testing.org", subject.getNameID().getValue()); assertEquals(NameIDType.EMAIL, subject.getNameID().getFormat()); SubjectConfirmation subjectConfirmation = subject.getSubjectConfirmations().get(0); SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData(); assertEquals(request.getID(), subjectConfirmationData.getInResponseTo()); verifyAssertionAttributes(authenticationId, assertion); }
if (assertion!= null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) { session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue()); break; continue; Signature encSig = assertion.getSignature(); if (idpMetadata.getSigningCertificate() != null && encSig != null) { BasicX509Credential sigCredential = new BasicX509Credential(); if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) { session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue()); username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());
assertionBean.getAttrBean() ); assertion.setIssuer(samlIssuer); org.opensaml.saml2.core.Conditions conditions = SAMLAssertionBuilder.createConditions(assertionBean.getConditionsBean()); assertion.setConditions(conditions); assertion.getAttributeStatements().addAll(attributeStatements); evidenceElement.getAssertions().add(assertion);
/** {@inheritDoc} */ protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { Assertion assertion = (Assertion) parentObject; if (childObject instanceof Issuer) { assertion.setIssuer((Issuer) childObject); } else if (childObject instanceof Signature) { assertion.setSignature((Signature) childObject); } else if (childObject instanceof Subject) { assertion.setSubject((Subject) childObject); } else if (childObject instanceof Conditions) { assertion.setConditions((Conditions) childObject); } else if (childObject instanceof Advice) { assertion.setAdvice((Advice) childObject); } else if (childObject instanceof Statement) { assertion.getStatements().add((Statement) childObject); } else { super.processChildElement(parentObject, childObject); } }
private void validateAssertion(Response response) throws SamlException { if (response.getAssertions().size() != 1) { throw new SamlException("The response doesn't contain exactly 1 assertion"); } Assertion assertion = response.getAssertions().get(0); if (!assertion.getIssuer().getValue().equals(responseIssuer)) { throw new SamlException("The assertion issuer didn't match the expected value"); } if (assertion.getSubject().getNameID() == null) { throw new SamlException( "The NameID value is missing from the SAML response; this is likely an IDP configuration issue"); } enforceConditions(assertion.getConditions()); }
/** {@inheritDoc} */ protected void doDecode(MessageContext messageContext) throws MessageDecodingException { if (!(messageContext instanceof SAMLMessageContext)) { log.error("Invalid message context type, this decoder only support SAMLMessageContext"); throw new MessageDecodingException( "Invalid message context type, this decoder only support SAMLMessageContext"); } if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) { log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport"); throw new MessageDecodingException( "Invalid inbound message transport type, this decoder only support HTTPInTransport"); } SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport(); if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) { throw new MessageDecodingException("This message decoder only supports the HTTP POST method"); } String relayState = inTransport.getParameterValue("RelayState"); samlMsgCtx.setRelayState(relayState); log.debug("Decoded SAML relay state of: {}", relayState); InputStream base64DecodedMessage = getBase64DecodedMessage(inTransport); Assertion inboundMessage = (Assertion) unmarshallMessage(base64DecodedMessage); Response response = SamlRedirectUtils.wrapAssertionIntoResponse(inboundMessage, inboundMessage.getIssuer().getValue()); samlMsgCtx.setInboundMessage(response); samlMsgCtx.setInboundSAMLMessage(response); log.debug("Decoded SAML message"); populateMessageContext(samlMsgCtx); }
/** * @return the SAML signature. */ @Override public Signature getSAMLSignature() { return assertion.getSignature(); }
protected void processSAMLAssertion() { this.setAssertionId(assertion.getID()); Subject subject = assertion.getSubject(); //Read the validity period from the 'Conditions' element, else read it from SC Data if (assertion.getConditions() != null) { Conditions conditions = assertion.getConditions(); if (conditions.getNotBefore() != null) { this.setDateNotBefore(conditions.getNotBefore().toDate()); } if (conditions.getNotOnOrAfter() != null) { this.setDateNotOnOrAfter(conditions.getNotOnOrAfter().toDate()); } } else { SubjectConfirmationData scData = subject.getSubjectConfirmations() .get(0).getSubjectConfirmationData(); if (scData.getNotBefore() != null) { this.setDateNotBefore(scData.getNotBefore().toDate()); } if (scData.getNotOnOrAfter() != null) { this.setDateNotOnOrAfter(scData.getNotOnOrAfter().toDate()); } } }