use of org.opensaml.saml.saml1.core.Conditions in project pac4j by pac4j.
the class SAML2Authenticator method validate.
@Override
public void validate(final SAML2Credentials credentials, final WebContext context) {
init();
final SAML2Profile profile = getProfileDefinition().newProfile();
final NameID nameId = credentials.getNameId();
profile.setId(nameId.getValue());
profile.addAttribute(SESSION_INDEX, credentials.getSessionIndex());
profile.addAuthenticationAttribute(SAML_NAME_ID_FORMAT, nameId.getFormat());
profile.addAuthenticationAttribute(SAML_NAME_ID_NAME_QUALIFIER, nameId.getNameQualifier());
profile.addAuthenticationAttribute(SAML_NAME_ID_SP_NAME_QUALIFIER, nameId.getSPNameQualifier());
profile.addAuthenticationAttribute(SAML_NAME_ID_SP_PROVIDED_ID, nameId.getSPProvidedID());
for (final Attribute attribute : credentials.getAttributes()) {
logger.debug("Processing profile attribute {}", attribute);
final String name = attribute.getName();
final String friendlyName = attribute.getFriendlyName();
final List<String> values = new ArrayList<>();
for (final XMLObject attributeValue : attribute.getAttributeValues()) {
final Element attributeValueElement = attributeValue.getDOM();
if (attributeValueElement != null) {
final String value = attributeValueElement.getTextContent();
logger.debug("Adding attribute value {} for attribute {} / {}", value, name, friendlyName);
values.add(value);
} else {
logger.warn("Attribute value DOM element is null for {}", attribute);
}
}
if (!values.isEmpty()) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, name, values);
if (CommonHelper.isNotBlank(friendlyName)) {
getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, friendlyName, values);
}
} else {
logger.debug("No attribute values found for {}", name);
}
}
// Add in issuerID and authnContexts
profile.addAuthenticationAttribute(ISSUER_ID, credentials.getIssuerId());
profile.addAuthenticationAttribute(AUTHN_CONTEXT, credentials.getAuthnContexts());
// Retrieve conditions attributes
// Adding them to both the "regular" and authentication attributes so we don't break anyone currently using it.
Conditions conditions = credentials.getConditions();
if (conditions != null) {
profile.addAttribute(SAML_CONDITION_NOT_BEFORE_ATTRIBUTE, conditions.getNotBefore());
profile.addAuthenticationAttribute(SAML_CONDITION_NOT_BEFORE_ATTRIBUTE, conditions.getNotBefore());
profile.addAttribute(SAML_CONDITION_NOT_ON_OR_AFTER_ATTRIBUTE, conditions.getNotOnOrAfter());
profile.addAuthenticationAttribute(SAML_CONDITION_NOT_ON_OR_AFTER_ATTRIBUTE, conditions.getNotOnOrAfter());
}
credentials.setUserProfile(profile);
}
use of org.opensaml.saml.saml1.core.Conditions in project MaxKey by dromara.
the class WsFederationUtils method createCredentialFromToken.
/**
* createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
*
* @param assertion the provided assertion
* @return an equivalent credential.
*/
public static WsFederationCredential createCredentialFromToken(final AssertionImpl assertion) {
final Logger _logger = LoggerFactory.getLogger(WsFederationUtils.class);
final DateTime retrievedOn = new DateTime().withZone(DateTimeZone.UTC);
_logger.debug("createCredentialFromToken: retrieved on {}", retrievedOn.toString());
final WsFederationCredential credential = new WsFederationCredential();
credential.setRetrievedOn(retrievedOn);
credential.setId(assertion.getID());
credential.setIssuer(assertion.getIssuer());
credential.setIssuedOn(assertion.getIssueInstant());
final Conditions conditions = assertion.getConditions();
if (conditions != null) {
credential.setNotBefore(conditions.getNotBefore());
credential.setNotOnOrAfter(conditions.getNotOnOrAfter());
credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getUri());
}
if (assertion.getAuthenticationStatements() != null && assertion.getAuthenticationStatements().size() > 0) {
credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
}
// retrieve an attributes from the assertion
final HashMap<String, Object> attributes = new HashMap<String, Object>();
for (Attribute item : assertion.getAttributeStatements().get(0).getAttributes()) {
_logger.debug("createCredentialFromToken: processed attribute: {}", item.getAttributeName());
if (item.getAttributeValues().size() == 1) {
attributes.put(item.getAttributeName(), ((XSAny) item.getAttributeValues().get(0)).getTextContent());
} else {
final ArrayList<String> itemList = new ArrayList<String>();
for (int i = 0; i < item.getAttributeValues().size(); i++) {
itemList.add(((XSAny) item.getAttributeValues().get(i)).getTextContent());
}
if (!itemList.isEmpty()) {
attributes.put(item.getAttributeName(), itemList);
}
}
}
credential.setAttributes(attributes);
_logger.debug("createCredentialFromToken: {}", credential.toString());
return credential;
}
use of org.opensaml.saml.saml1.core.Conditions in project MaxKey by dromara.
the class AssertionGenerator method generateAssertion.
public Assertion generateAssertion(AppsSAML20Details saml20Details, BindingAdapter bindingAdapter, String assertionConsumerURL, String inResponseTo, String audienceUrl, int validInSeconds, HashMap<String, String> attributeMap) {
Assertion assertion = new AssertionBuilder().buildObject();
;
// Subject
Subject subject = subjectGenerator.generateSubject(saml20Details, assertionConsumerURL, inResponseTo, validInSeconds);
assertion.setSubject(subject);
// issuer
Issuer issuer = issuerGenerator.generateIssuer();
assertion.setIssuer(issuer);
// AuthnStatements
DateTime authnInstant = new DateTime(WebContext.getSession().getCreationTime());
AuthnStatement authnStatement = authnStatementGenerator.generateAuthnStatement(authnInstant);
assertion.getAuthnStatements().add(authnStatement);
// AttributeStatements
ArrayList<GrantedAuthority> grantedAuthoritys = new ArrayList<GrantedAuthority>();
grantedAuthoritys.add(new SimpleGrantedAuthority("ROLE_USER"));
for (GrantedAuthority anthGrantedAuthority : ((UsernamePasswordAuthenticationToken) WebContext.getAuthentication()).getAuthorities()) {
grantedAuthoritys.add(anthGrantedAuthority);
}
AttributeStatement attributeStatement = attributeStatementGenerator.generateAttributeStatement(saml20Details, grantedAuthoritys, attributeMap);
assertion.getAttributeStatements().add(attributeStatement);
// ID
assertion.setID(idService.generateID());
// IssueInstant
assertion.setIssueInstant(timeService.getCurrentDateTime());
// Conditions
Conditions conditions = conditionsGenerator.generateConditions(audienceUrl, validInSeconds);
assertion.setConditions(conditions);
// sign Assertion
try {
if (bindingAdapter.getSigningCredential() == null) {
throw new Exception("Signing Credential is null...");
}
logger.debug("EntityId " + bindingAdapter.getSigningCredential().getEntityId());
BasicCredential basicCredential = new BasicCredential();
basicCredential.setPrivateKey(bindingAdapter.getSigningCredential().getPrivateKey());
Signature signature = new SignatureBuilder().buildObject();
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
signature.setSigningCredential(basicCredential);
KeyInfoGeneratorFactory keyInfoGeneratorFactory = Configuration.getGlobalSecurityConfiguration().getKeyInfoGeneratorManager().getDefaultManager().getFactory(bindingAdapter.getSigningCredential());
signature.setKeyInfo(keyInfoGeneratorFactory.newInstance().generate(bindingAdapter.getSigningCredential()));
BasicSecurityConfiguration config = (BasicSecurityConfiguration) Configuration.getGlobalSecurityConfiguration();
if (saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA1")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
} else if (saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA256")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
} else if (saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA384")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA384);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA384);
} else if (saml20Details.getSignature().equalsIgnoreCase("RSAwithSHA512")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512);
} else if (saml20Details.getSignature().equalsIgnoreCase("RSAwithMD5")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5);
} else if (saml20Details.getSignature().equalsIgnoreCase("RSAwithRIPEMD160")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_RIPEMD160);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_RIPEMD160);
} else if (saml20Details.getSignature().equalsIgnoreCase("DSAwithSHA1")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1);
} else if (saml20Details.getSignature().equalsIgnoreCase("ECDSAwithSHA256")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256);
} else if (saml20Details.getSignature().equalsIgnoreCase("ECDSAwithSHA384")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA384);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA384);
} else if (saml20Details.getSignature().equalsIgnoreCase("ECDSAwithSHA512")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA512);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA512);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-MD5")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-SHA1")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_SHA1);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-SHA256")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_SHA256);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_SHA256);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-SHA384")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_SHA384);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_SHA384);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-SHA512")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_SHA512);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_SHA512);
} else if (saml20Details.getSignature().equalsIgnoreCase("HMAC-RIPEMD160")) {
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_MAC_HMAC_RIPEMD160);
config.registerSignatureAlgorithmURI(saml20Details.getSignature(), SignatureConstants.ALGO_ID_MAC_HMAC_RIPEMD160);
}
if (saml20Details.getDigestMethod().equalsIgnoreCase("MD5")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5);
} else if (saml20Details.getDigestMethod().equalsIgnoreCase("SHA1")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA1);
} else if (saml20Details.getDigestMethod().equalsIgnoreCase("SHA256")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256);
} else if (saml20Details.getDigestMethod().equalsIgnoreCase("SHA384")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA384);
} else if (saml20Details.getDigestMethod().equalsIgnoreCase("SHA512")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA512);
} else if (saml20Details.getDigestMethod().equalsIgnoreCase("RIPEMD-160")) {
config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_RIPEMD160);
}
assertion.setSignature(signature);
Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);
Signer.signObject(signature);
logger.debug("assertion.isSigned " + assertion.isSigned());
} catch (Exception e) {
e.printStackTrace();
logger.info("Unable to Signer assertion ", e);
}
return assertion;
}
use of org.opensaml.saml.saml1.core.Conditions in project security by opensearch-project.
the class MockSamlIdpServer method createSamlAuthResponse.
private String createSamlAuthResponse(AuthnRequest authnRequest) {
try {
Response response = createSamlElement(Response.class);
response.setID(nextId());
if (authnRequest != null) {
response.setInResponseTo(authnRequest.getID());
}
response.setVersion(SAMLVersion.VERSION_20);
response.setStatus(createStatus(StatusCode.SUCCESS));
response.setIssueInstant(new DateTime());
Assertion assertion = createSamlElement(Assertion.class);
assertion.setID(nextId());
assertion.setIssueInstant(new DateTime());
assertion.setIssuer(createIssuer());
AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
assertion.getAuthnStatements().add(authnStatement);
authnStatement.setAuthnInstant(new DateTime());
authnStatement.setSessionIndex(nextId());
authnStatement.setAuthnContext(createAuthnCotext());
Subject subject = createSamlElement(Subject.class);
assertion.setSubject(subject);
subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));
if (authnRequest != null) {
subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer", new DateTime().plusMinutes(1), authnRequest.getID(), authnRequest.getAssertionConsumerServiceURL()));
} else {
subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer", new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
}
Conditions conditions = createSamlElement(Conditions.class);
assertion.setConditions(conditions);
conditions.setNotBefore(new DateTime());
conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));
if (authenticateUserRoles != null) {
AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
assertion.getAttributeStatements().add(attributeStatement);
Attribute attribute = createSamlElement(Attribute.class);
attributeStatement.getAttributes().add(attribute);
attribute.setName("roles");
attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");
for (String role : authenticateUserRoles) {
attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
}
}
if (signResponses) {
Signature signature = createSamlElement(Signature.class);
assertion.setSignature(signature);
signature.setSigningCredential(this.signingCredential);
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);
Signer.signObject(signature);
}
if (this.encryptAssertion) {
Encrypter encrypter = getEncrypter();
EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion);
response.getEncryptedAssertions().add(encryptedAssertion);
} else {
response.getAssertions().add(assertion);
}
String marshalledXml = marshallSamlXml(response);
return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);
} catch (MarshallingException | SignatureException | UnsupportedEncodingException | EncryptionException e) {
throw new RuntimeException(e);
}
}
use of org.opensaml.saml.saml1.core.Conditions in project OpenUnison by TremoloSecurity.
the class Saml2Assertion method generateAssertion.
private Assertion generateAssertion(String id2) {
byte[] idBytes = new byte[20];
random.nextBytes(idBytes);
StringBuffer b = new StringBuffer();
b.append('f').append(Hex.encodeHexString(idBytes));
String id = b.toString();
AssertionBuilder assertionBuilder = new AssertionBuilder();
Assertion assertion = assertionBuilder.buildObject();
assertion.setID(id);
IssuerBuilder issuerBuilder = new IssuerBuilder();
Issuer issuer = issuerBuilder.buildObject();
issuer.setValue(this.issuer);
assertion.setIssuer(issuer);
// Get the subject builder based on the subject element name
SubjectBuilder builder = new SubjectBuilder();
// Create the subject
Subject subject = builder.buildObject();
SubjectConfirmationBuilder scb = new SubjectConfirmationBuilder();
SubjectConfirmation sc = scb.buildObject();
sc.setMethod(SubjectConfirmation.METHOD_BEARER);
SubjectConfirmationDataBuilder scdb = new SubjectConfirmationDataBuilder();
SubjectConfirmationData scd = scdb.buildObject();
scd.setNotOnOrAfter(this.notAfter);
scd.setRecipient(this.recepient);
sc.setSubjectConfirmationData(scd);
subject.getSubjectConfirmations().add(sc);
NameIDBuilder nameIDBuilder = new NameIDBuilder();
NameID nameID = nameIDBuilder.buildObject();
nameID.setValue(this.subject);
nameID.setFormat(this.nameIDFormat);
// Added an NameID and two SubjectConfirmation items - creation of these items is not shown
subject.setNameID(nameID);
assertion.setSubject(subject);
AuthnStatementBuilder authnStmtBuilder = new AuthnStatementBuilder();
AuthnStatement authn = authnStmtBuilder.buildObject();
authn.setAuthnInstant(this.issueInstant);
AuthnContextBuilder authnCtxBuilder = new AuthnContextBuilder();
AuthnContext authnCtx = authnCtxBuilder.buildObject();
AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
AuthnContextClassRef accrf = accrb.buildObject();
accrf.setURI(this.authnContextRef);
authnCtx.setAuthnContextClassRef(accrf);
authn.setAuthnContext(authnCtx);
// AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
// AuthnContextClassRef accr = accrb.buildObject();
// accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified");
authn.setSessionIndex(id);
// authnCtx.setAuthnContextClassRef(accr);
// authn.setAuthnContext(authnCtx);
assertion.getAuthnStatements().add(authn);
AttributeStatementBuilder attrb = new AttributeStatementBuilder();
AttributeStatement attrStmt = attrb.buildObject();
boolean addAttrs = false;
Iterator<Attribute> attrs = this.attribs.iterator();
while (attrs.hasNext()) {
Attribute attrib = attrs.next();
AttributeBuilder attrBuilder = new AttributeBuilder();
org.opensaml.saml.saml2.core.Attribute samlAttrib = attrBuilder.buildObject();
samlAttrib.setName(attrib.getName());
Iterator<String> attrVals = attrib.getValues().iterator();
while (attrVals.hasNext()) {
XSStringBuilder sb = new XSStringBuilder();
XSString val = sb.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
val.setValue(attrVals.next());
samlAttrib.getAttributeValues().add(val);
addAttrs = true;
}
attrStmt.getAttributes().add(samlAttrib);
}
if (addAttrs) {
assertion.getAttributeStatements().add(attrStmt);
}
ConditionsBuilder cb = new ConditionsBuilder();
Conditions conditions = cb.buildObject();
conditions.setNotBefore(this.notBefore);
conditions.setNotOnOrAfter(this.notAfter);
AudienceRestrictionBuilder arb = new AudienceRestrictionBuilder();
AudienceRestriction ar = arb.buildObject();
AudienceBuilder ab = new AudienceBuilder();
Audience a = ab.buildObject();
a.setURI(this.audience);
ar.getAudiences().add(a);
conditions.getAudienceRestrictions().add(ar);
assertion.setConditions(conditions);
assertion.setIssueInstant(this.issueInstant);
return assertion;
}
Aggregations