use of org.opensaml.saml2.core.AuthnStatement in project cxf by apache.
the class SAMLSSOResponseValidator method validateSamlResponse.
/**
* Validate a SAML 2 Protocol Response
* @param samlResponse
* @param postBinding
* @return a SSOValidatorResponse object
* @throws WSSecurityException
*/
public SSOValidatorResponse validateSamlResponse(org.opensaml.saml.saml2.core.Response samlResponse, boolean postBinding) throws WSSecurityException {
// Check the Issuer
validateIssuer(samlResponse.getIssuer());
// The Response must contain at least one Assertion.
if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) {
LOG.warning("The Response must contain at least one Assertion");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
// The Response must contain a Destination that matches the assertionConsumerURL if it is
// signed
String destination = samlResponse.getDestination();
if (samlResponse.isSigned() && (destination == null || !destination.equals(assertionConsumerURL))) {
LOG.warning("The Response must contain a destination that matches the assertion consumer URL");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
if (enforceResponseSigned && !samlResponse.isSigned()) {
LOG.warning("The Response must be signed!");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
// Validate Assertions
org.opensaml.saml.saml2.core.Assertion validAssertion = null;
Instant sessionNotOnOrAfter = null;
for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
// Check the Issuer
if (assertion.getIssuer() == null) {
LOG.warning("Assertion Issuer must not be null");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
validateIssuer(assertion.getIssuer());
if (!samlResponse.isSigned() && enforceAssertionsSigned && assertion.getSignature() == null) {
LOG.warning("The enclosed assertions in the SAML Response must be signed");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
// Check for AuthnStatements and validate the Subject accordingly
if (assertion.getAuthnStatements() != null && !assertion.getAuthnStatements().isEmpty()) {
org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject();
org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf = validateAuthenticationSubject(subject, assertion.getID(), postBinding);
if (subjectConf != null) {
validateAudienceRestrictionCondition(assertion.getConditions());
validAssertion = assertion;
sessionNotOnOrAfter = null;
// Store Session NotOnOrAfter
for (AuthnStatement authnStatment : assertion.getAuthnStatements()) {
if (authnStatment.getSessionNotOnOrAfter() != null) {
sessionNotOnOrAfter = Instant.ofEpochMilli(authnStatment.getSessionNotOnOrAfter().toDate().getTime());
}
}
// Fall back to the SubjectConfirmationData NotOnOrAfter if we have no session NotOnOrAfter
if (sessionNotOnOrAfter == null) {
sessionNotOnOrAfter = Instant.ofEpochMilli(subjectConf.getSubjectConfirmationData().getNotOnOrAfter().toDate().getTime());
}
}
}
}
if (validAssertion == null) {
LOG.warning("The Response did not contain any Authentication Statement that matched " + "the Subject Confirmation criteria");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
SSOValidatorResponse validatorResponse = new SSOValidatorResponse();
validatorResponse.setResponseId(samlResponse.getID());
validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter);
if (samlResponse.getIssueInstant() != null) {
validatorResponse.setCreated(Instant.ofEpochMilli(samlResponse.getIssueInstant().toDate().getTime()));
}
Element assertionElement = validAssertion.getDOM();
Element clonedAssertionElement = (Element) assertionElement.cloneNode(true);
validatorResponse.setAssertionElement(clonedAssertionElement);
validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement));
validatorResponse.setOpensamlAssertion(validAssertion);
return validatorResponse;
}
use of org.opensaml.saml2.core.AuthnStatement in project cas by apereo.
the class SamlProfileSamlAuthNStatementBuilder method buildAuthnStatement.
/**
* Creates an authentication statement for the current request.
*
* @param assertion the assertion
* @param authnRequest the authn request
* @param adaptor the adaptor
* @param service the service
* @return constructed authentication statement
* @throws SamlException the saml exception
*/
private AuthnStatement buildAuthnStatement(final Assertion assertion, final AuthnRequest authnRequest, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final SamlRegisteredService service) throws SamlException {
final String authenticationMethod = this.authnContextClassRefBuilder.build(assertion, authnRequest, adaptor, service);
final String id = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
final AuthnStatement statement = newAuthnStatement(authenticationMethod, DateTimeUtils.zonedDateTimeOf(assertion.getAuthenticationDate()), id);
if (assertion.getValidUntilDate() != null) {
final ZonedDateTime dt = DateTimeUtils.zonedDateTimeOf(assertion.getValidUntilDate());
statement.setSessionNotOnOrAfter(DateTimeUtils.dateTimeOf(dt.plusSeconds(casProperties.getAuthn().getSamlIdp().getResponse().getSkewAllowance())));
}
statement.setSubjectLocality(buildSubjectLocality(assertion, authnRequest, adaptor));
return statement;
}
use of org.opensaml.saml2.core.AuthnStatement in project cas by apereo.
the class SamlProfileSamlAssertionBuilder method build.
@Override
public Assertion build(final RequestAbstractType authnRequest, final HttpServletRequest request, final HttpServletResponse response, final Object casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
final List<Statement> statements = new ArrayList<>();
final AuthnStatement authnStatement = this.samlProfileSamlAuthNStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
statements.add(authnStatement);
final AttributeStatement attrStatement = this.samlProfileSamlAttributeStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
if (!attrStatement.getAttributes().isEmpty() || !attrStatement.getEncryptedAttributes().isEmpty()) {
statements.add(attrStatement);
}
final String id = '_' + String.valueOf(Math.abs(RandomUtils.getNativeInstance().nextLong()));
final Assertion assertion = newAssertion(statements, casProperties.getAuthn().getSamlIdp().getEntityId(), ZonedDateTime.now(ZoneOffset.UTC), id);
assertion.setSubject(this.samlProfileSamlSubjectBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
assertion.setConditions(this.samlProfileSamlConditionsBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
signAssertion(assertion, request, response, service, adaptor, binding);
return assertion;
}
use of org.opensaml.saml2.core.AuthnStatement in project pac4j by pac4j.
the class SAML2DefaultResponseValidator method buildSAML2Credentials.
protected final SAML2Credentials buildSAML2Credentials(final SAML2MessageContext context) {
final NameID nameId = context.getSAMLSubjectNameIdentifierContext().getSAML2SubjectNameID();
final Assertion subjectAssertion = context.getSubjectAssertion();
final String sessionIndex = getSessionIndex(subjectAssertion);
final String issuerEntityId = subjectAssertion.getIssuer().getValue();
List<AuthnStatement> authnStatements = subjectAssertion.getAuthnStatements();
List<String> authnContexts = new ArrayList<String>();
for (AuthnStatement authnStatement : authnStatements) {
authnContexts.add(authnStatement.getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
}
final List<Attribute> attributes = new ArrayList<Attribute>();
for (final AttributeStatement attributeStatement : subjectAssertion.getAttributeStatements()) {
for (final Attribute attribute : attributeStatement.getAttributes()) {
attributes.add(attribute);
}
if (!attributeStatement.getEncryptedAttributes().isEmpty()) {
if (decrypter == null) {
logger.warn("Encrypted attributes returned, but no keystore was provided.");
} else {
for (final EncryptedAttribute encryptedAttribute : attributeStatement.getEncryptedAttributes()) {
try {
attributes.add(decrypter.decrypt(encryptedAttribute));
} catch (final DecryptionException e) {
logger.warn("Decryption of attribute failed, continue with the next one", e);
}
}
}
}
}
return new SAML2Credentials(nameId, issuerEntityId, attributes, subjectAssertion.getConditions(), sessionIndex, authnContexts);
}
use of org.opensaml.saml2.core.AuthnStatement in project ddf by codice.
the class SamlAssertionValidatorImplTest method createAssertion.
private Assertion createAssertion(boolean sign, boolean validSignature, String issuerString, DateTime notOnOrAfter) throws Exception {
Assertion assertion = new AssertionBuilder().buildObject();
assertion.setID(UUID.randomUUID().toString());
assertion.setIssueInstant(new DateTime());
Issuer issuer = new IssuerBuilder().buildObject();
issuer.setValue(issuerString);
assertion.setIssuer(issuer);
NameID nameID = new NameIDBuilder().buildObject();
nameID.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
nameID.setNameQualifier("http://cxf.apache.org/sts");
nameID.setValue("admin");
SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject();
subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
Subject subject = new SubjectBuilder().buildObject();
subject.setNameID(nameID);
subject.getSubjectConfirmations().add(subjectConfirmation);
assertion.setSubject(subject);
Conditions conditions = new ConditionsBuilder().buildObject();
conditions.setNotBefore(new DateTime().minusDays(3));
conditions.setNotOnOrAfter(notOnOrAfter);
assertion.setConditions(conditions);
AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
authnStatement.setAuthnInstant(new DateTime());
AuthnContext authnContext = new AuthnContextBuilder().buildObject();
AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified");
authnContext.setAuthnContextClassRef(authnContextClassRef);
authnStatement.setAuthnContext(authnContext);
assertion.getAuthnStatements().add(authnStatement);
AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
Attribute attribute = new AttributeBuilder().buildObject();
AttributeValueType attributeValue = new AttributeValueTypeImplBuilder().buildObject();
attributeValue.setValue("admin");
attribute.setName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");
attribute.getAttributeValues().add(attributeValue);
attributeStatement.getAttributes().add(attribute);
assertion.getAttributeStatements().add(attributeStatement);
if (sign) {
Signature signature = OpenSAMLUtil.buildSignature();
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
signature.setSignatureAlgorithm(WSS4JConstants.RSA);
BasicX509Credential signingCredential;
if (validSignature) {
signingCredential = new BasicX509Credential(certificate);
signingCredential.setPrivateKey(privateKey);
signature.setSigningCredential(signingCredential);
} else {
try (InputStream inputStream = getClass().getResourceAsStream("/localhost.crt")) {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(inputStream);
signingCredential = new BasicX509Credential(cert);
signature.setSigningCredential(signingCredential);
}
}
X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true);
KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential);
signature.setKeyInfo(keyInfo);
assertion.setSignature(signature);
}
return assertion;
}
Aggregations