use of org.opensaml.saml2.core.Attribute in project syncope by apache.
the class SAML2SPLogic method validateLoginResponse.
@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2LoginResponseTO validateLoginResponse(final SAML2ReceivedResponseTO response) {
check();
// 1. first checks for the provided relay state
if (response.getRelayState() == null) {
throw new IllegalArgumentException("No Relay State was provided");
}
Boolean useDeflateEncoding = false;
String requestId = null;
if (!IDP_INITIATED_RELAY_STATE.equals(response.getRelayState())) {
JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
if (!relayState.verifySignatureWith(jwsSignatureVerifier)) {
throw new IllegalArgumentException("Invalid signature found in Relay State");
}
useDeflateEncoding = Boolean.valueOf(relayState.getJwtClaims().getClaim(JWT_CLAIM_IDP_DEFLATE).toString());
requestId = relayState.getJwtClaims().getSubject();
Long expiryTime = relayState.getJwtClaims().getExpiryTime();
if (expiryTime == null || (expiryTime * 1000L) < new Date().getTime()) {
throw new IllegalArgumentException("Relay State is expired");
}
}
// 2. parse the provided SAML response
if (response.getSamlResponse() == null) {
throw new IllegalArgumentException("No SAML Response was provided");
}
Response samlResponse;
try {
XMLObject responseObject = saml2rw.read(useDeflateEncoding, response.getSamlResponse());
if (!(responseObject instanceof Response)) {
throw new IllegalArgumentException("Expected " + Response.class.getName() + ", got " + responseObject.getClass().getName());
}
samlResponse = (Response) responseObject;
} catch (Exception e) {
LOG.error("While parsing AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 3. validate the SAML response and, if needed, decrypt the provided assertion(s)
if (samlResponse.getIssuer() == null || samlResponse.getIssuer().getValue() == null) {
throw new IllegalArgumentException("The SAML Response must contain an Issuer");
}
final SAML2IdPEntity idp = getIdP(samlResponse.getIssuer().getValue());
if (idp.getConnObjectKeyItem() == null) {
throw new IllegalArgumentException("No mapping provided for SAML 2.0 IdP '" + idp.getId() + "'");
}
if (IDP_INITIATED_RELAY_STATE.equals(response.getRelayState()) && !idp.isSupportUnsolicited()) {
throw new IllegalArgumentException("An unsolicited request is not allowed for idp: " + idp.getId());
}
SSOValidatorResponse validatorResponse = null;
try {
validatorResponse = saml2rw.validate(samlResponse, idp, getAssertionConsumerURL(response.getSpEntityID(), response.getUrlContext()), requestId, response.getSpEntityID());
} catch (Exception e) {
LOG.error("While validating AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 4. prepare the result: find matching user (if any) and return the received attributes
final SAML2LoginResponseTO responseTO = new SAML2LoginResponseTO();
responseTO.setIdp(idp.getId());
responseTO.setSloSupported(idp.getSLOLocation(idp.getBindingType()) != null);
Assertion assertion = validatorResponse.getOpensamlAssertion();
NameID nameID = assertion.getSubject().getNameID();
if (nameID == null) {
throw new IllegalArgumentException("NameID not found");
}
String keyValue = null;
if (StringUtils.isNotBlank(nameID.getValue()) && idp.getConnObjectKeyItem().getExtAttrName().equals("NameID")) {
keyValue = nameID.getValue();
}
if (assertion.getConditions().getNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(assertion.getConditions().getNotOnOrAfter().toDate());
}
assertion.getAuthnStatements().forEach(authnStmt -> {
responseTO.setSessionIndex(authnStmt.getSessionIndex());
responseTO.setAuthInstant(authnStmt.getAuthnInstant().toDate());
if (authnStmt.getSessionNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(authnStmt.getSessionNotOnOrAfter().toDate());
}
});
for (AttributeStatement attrStmt : assertion.getAttributeStatements()) {
for (Attribute attr : attrStmt.getAttributes()) {
if (!attr.getAttributeValues().isEmpty()) {
String attrName = attr.getFriendlyName() == null ? attr.getName() : attr.getFriendlyName();
if (attrName.equals(idp.getConnObjectKeyItem().getExtAttrName())) {
if (attr.getAttributeValues().get(0) instanceof XSString) {
keyValue = ((XSString) attr.getAttributeValues().get(0)).getValue();
} else if (attr.getAttributeValues().get(0) instanceof XSAny) {
keyValue = ((XSAny) attr.getAttributeValues().get(0)).getTextContent();
}
}
AttrTO attrTO = new AttrTO();
attrTO.setSchema(attrName);
attr.getAttributeValues().stream().filter(value -> value.getDOM() != null).forEachOrdered(value -> {
attrTO.getValues().add(value.getDOM().getTextContent());
});
responseTO.getAttrs().add(attrTO);
}
}
}
final List<String> matchingUsers = keyValue == null ? Collections.<String>emptyList() : userManager.findMatchingUser(keyValue, idp.getKey());
LOG.debug("Found {} matching users for {}", matchingUsers.size(), keyValue);
String username;
if (matchingUsers.isEmpty()) {
if (idp.isCreateUnmatching()) {
LOG.debug("No user matching {}, about to create", keyValue);
username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.create(idp, responseTO, nameID.getValue()));
} else if (idp.isSelfRegUnmatching()) {
responseTO.setNameID(nameID.getValue());
UserTO userTO = new UserTO();
userManager.fill(idp.getKey(), responseTO, userTO);
responseTO.getAttrs().clear();
responseTO.getAttrs().addAll(userTO.getPlainAttrs());
responseTO.getAttrs().addAll(userTO.getVirAttrs());
if (StringUtils.isNotBlank(userTO.getUsername())) {
responseTO.setUsername(userTO.getUsername());
}
responseTO.setSelfReg(true);
return responseTO;
} else {
throw new NotFoundException("User matching the provided value " + keyValue);
}
} else if (matchingUsers.size() > 1) {
throw new IllegalArgumentException("Several users match the provided value " + keyValue);
} else {
if (idp.isUpdateMatching()) {
LOG.debug("About to update {} for {}", matchingUsers.get(0), keyValue);
username = AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> userManager.update(matchingUsers.get(0), idp, responseTO));
} else {
username = matchingUsers.get(0);
}
}
responseTO.setUsername(username);
responseTO.setNameID(nameID.getValue());
// 5. generate JWT for further access
Map<String, Object> claims = new HashMap<>();
claims.put(JWT_CLAIM_IDP_ENTITYID, idp.getId());
claims.put(JWT_CLAIM_NAMEID_FORMAT, nameID.getFormat());
claims.put(JWT_CLAIM_NAMEID_VALUE, nameID.getValue());
claims.put(JWT_CLAIM_SESSIONINDEX, responseTO.getSessionIndex());
byte[] authorities = null;
try {
authorities = ENCRYPTOR.encode(POJOHelper.serialize(authDataAccessor.getAuthorities(responseTO.getUsername())), CipherAlgorithm.AES).getBytes();
} catch (Exception e) {
LOG.error("Could not fetch authorities", e);
}
Pair<String, Date> accessTokenInfo = accessTokenDataBinder.create(responseTO.getUsername(), claims, authorities, true);
responseTO.setAccessToken(accessTokenInfo.getLeft());
responseTO.setAccessTokenExpiryTime(accessTokenInfo.getRight());
return responseTO;
}
use of org.opensaml.saml2.core.Attribute in project webcert by sklintyg.
the class BaseFakeAuthenticationProvider method createAttribute.
protected Attribute createAttribute(String name, String value) {
Attribute attribute = new AttributeBuilder().buildObject();
attribute.setName(name);
Document doc = documentBuilder.newDocument();
Element element = doc.createElement("element");
element.setTextContent(value);
XMLObject xmlObject = new XSStringBuilder().buildObject(new QName("ns", "local"));
xmlObject.setDOM(element);
attribute.getAttributeValues().add(xmlObject);
return attribute;
}
use of org.opensaml.saml2.core.Attribute 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;
}
use of org.opensaml.saml2.core.Attribute in project carbon-apimgt by wso2.
the class SystemScopeUtils method getRolesFromAssertion.
/**
* Get the role list from the SAML2 Assertion
*
* @param assertion SAML2 assertion
* @return Role list from the assertion
*/
public static String[] getRolesFromAssertion(Assertion assertion) {
List<String> roles = new ArrayList<String>();
String roleClaim = getRoleClaim();
List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();
if (attributeStatementList != null) {
for (AttributeStatement statement : attributeStatementList) {
List<Attribute> attributesList = statement.getAttributes();
for (Attribute attribute : attributesList) {
String attributeName = attribute.getName();
if (attributeName != null && roleClaim.equals(attributeName)) {
List<XMLObject> attributeValues = attribute.getAttributeValues();
if (attributeValues != null && attributeValues.size() == 1) {
String attributeValueString = getAttributeValue(attributeValues.get(0));
String multiAttributeSeparator = getAttributeSeparator();
String[] attributeValuesArray = attributeValueString.split(multiAttributeSeparator);
if (log.isDebugEnabled()) {
log.debug("Adding attributes for Assertion: " + assertion + " AttributeName : " + attributeName + ", AttributeValue : " + Arrays.toString(attributeValuesArray));
}
roles.addAll(Arrays.asList(attributeValuesArray));
} else if (attributeValues != null && attributeValues.size() > 1) {
for (XMLObject attributeValue : attributeValues) {
String attributeValueString = getAttributeValue(attributeValue);
if (log.isDebugEnabled()) {
log.debug("Adding attributes for Assertion: " + assertion + " AttributeName : " + attributeName + ", AttributeValue : " + attributeValue);
}
roles.add(attributeValueString);
}
}
}
}
}
}
if (log.isDebugEnabled()) {
log.debug("Role list found for assertion: " + assertion + ", roles: " + roles);
}
return roles.toArray(new String[roles.size()]);
}
use of org.opensaml.saml2.core.Attribute in project cxf by apache.
the class SAMLClaimsTest method testSaml2StaticClaims.
/**
* Test the creation of a SAML2 Assertion with StaticClaimsHandler
*/
@org.junit.Test
public void testSaml2StaticClaims() throws Exception {
TokenProvider samlTokenProvider = new SAMLTokenProvider();
TokenProviderParameters providerParameters = createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);
ClaimsManager claimsManager = new ClaimsManager();
StaticClaimsHandler claimsHandler = new StaticClaimsHandler();
Map<String, String> staticClaimsMap = new HashMap<>();
staticClaimsMap.put(CLAIM_STATIC_COMPANY, CLAIM_STATIC_COMPANY_VALUE);
claimsHandler.setGlobalClaims(staticClaimsMap);
claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler) claimsHandler));
providerParameters.setClaimsManager(claimsManager);
ClaimCollection claims = new ClaimCollection();
Claim claim = new Claim();
claim.setClaimType(CLAIM_STATIC_COMPANY);
claims.add(claim);
providerParameters.setRequestedPrimaryClaims(claims);
assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
assertNotNull(providerResponse);
assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
Element token = (Element) providerResponse.getToken();
String tokenString = DOM2Writer.nodeToString(token);
assertTrue(tokenString.contains(providerResponse.getTokenId()));
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("alice"));
assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
List<Attribute> attributes = assertion.getSaml2().getAttributeStatements().get(0).getAttributes();
assertEquals(attributes.size(), 1);
assertEquals(attributes.get(0).getName(), CLAIM_STATIC_COMPANY);
XMLObject valueObj = attributes.get(0).getAttributeValues().get(0);
assertEquals(valueObj.getDOM().getTextContent(), CLAIM_STATIC_COMPANY_VALUE);
}
Aggregations