use of org.opensaml.saml2.core.Attribute in project spring-security by spring-projects.
the class OpenSamlAuthenticationProviderTests method attributeStatements.
private List<AttributeStatement> attributeStatements() {
List<AttributeStatement> attributeStatements = TestOpenSamlObjects.attributeStatements();
AttributeBuilder attributeBuilder = new AttributeBuilder();
Attribute registeredDateAttr = attributeBuilder.buildObject();
registeredDateAttr.setName("registeredDate");
XSDateTime registeredDate = new XSDateTimeBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSDateTime.TYPE_NAME);
registeredDate.setValue(DateTime.parse("1970-01-01T00:00:00Z"));
registeredDateAttr.getAttributeValues().add(registeredDate);
attributeStatements.get(0).getAttributes().add(registeredDateAttr);
return attributeStatements;
}
use of org.opensaml.saml2.core.Attribute in project spring-security by spring-projects.
the class OpenSamlAuthenticationProvider method getAssertionAttributes.
private static Map<String, List<Object>> getAssertionAttributes(Assertion assertion) {
Map<String, List<Object>> attributeMap = new LinkedHashMap<>();
for (AttributeStatement attributeStatement : assertion.getAttributeStatements()) {
for (Attribute attribute : attributeStatement.getAttributes()) {
List<Object> attributeValues = new ArrayList<>();
for (XMLObject xmlObject : attribute.getAttributeValues()) {
Object attributeValue = getXmlObjectValue(xmlObject);
if (attributeValue != null) {
attributeValues.add(attributeValue);
}
}
attributeMap.put(attribute.getName(), attributeValues);
}
}
return attributeMap;
}
use of org.opensaml.saml2.core.Attribute in project spring-security by spring-projects.
the class OpenSaml4AuthenticationProviderTests method attributeStatements.
private List<AttributeStatement> attributeStatements() {
List<AttributeStatement> attributeStatements = TestOpenSamlObjects.attributeStatements();
AttributeBuilder attributeBuilder = new AttributeBuilder();
Attribute registeredDateAttr = attributeBuilder.buildObject();
registeredDateAttr.setName("registeredDate");
XSDateTime registeredDate = new XSDateTimeBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSDateTime.TYPE_NAME);
registeredDate.setValue(Instant.parse("1970-01-01T00:00:00Z"));
registeredDateAttr.getAttributeValues().add(registeredDate);
attributeStatements.iterator().next().getAttributes().add(registeredDateAttr);
return attributeStatements;
}
use of org.opensaml.saml2.core.Attribute in project cloudstack by apache.
the class SAML2LoginAPIAuthenticatorCmd method authenticate.
@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, final InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
try {
if (!params.containsKey(SAMLPluginConstants.SAML_RESPONSE) && !params.containsKey("SAMLart")) {
String idpId = null;
String domainPath = null;
if (params.containsKey(ApiConstants.IDP_ID)) {
idpId = ((String[]) params.get(ApiConstants.IDP_ID))[0];
}
if (params.containsKey(ApiConstants.DOMAIN)) {
domainPath = ((String[]) params.get(ApiConstants.DOMAIN))[0];
}
if (domainPath != null && !domainPath.isEmpty()) {
if (!domainPath.startsWith("/")) {
domainPath = "/" + domainPath;
}
if (!domainPath.endsWith("/")) {
domainPath = domainPath + "/";
}
}
SAMLProviderMetadata spMetadata = samlAuthManager.getSPMetadata();
SAMLProviderMetadata idpMetadata = samlAuthManager.getIdPMetadata(idpId);
if (idpMetadata == null) {
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") is not found in our list of supported IdPs, cannot proceed.", params, responseType));
}
if (idpMetadata.getSsoUrl() == null || idpMetadata.getSsoUrl().isEmpty()) {
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") has no Single Sign On URL defined please contact " + idpMetadata.getContactPersonName() + " <" + idpMetadata.getContactPersonEmail() + ">, cannot proceed.", params, responseType));
}
String authnId = SAMLUtils.generateSecureRandomId();
samlAuthManager.saveToken(authnId, domainPath, idpMetadata.getEntityId());
s_logger.debug("Sending SAMLRequest id=" + authnId);
String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value());
resp.sendRedirect(redirectUrl);
return "";
}
if (params.containsKey("SAMLart")) {
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, apiServer.getSerializedApiError(ApiErrorCode.UNSUPPORTED_ACTION_ERROR.getHttpCode(), "SAML2 HTTP Artifact Binding is not supported", params, responseType));
} else {
final String samlResponse = ((String[]) params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
Response processedSAMLResponse = this.processSAMLResponse(samlResponse);
String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Identity Provider send a non-successful authentication status code", params, responseType));
}
String username = null;
Issuer issuer = processedSAMLResponse.getIssuer();
SAMLProviderMetadata spMetadata = samlAuthManager.getSPMetadata();
SAMLProviderMetadata idpMetadata = samlAuthManager.getIdPMetadata(issuer.getValue());
String responseToId = processedSAMLResponse.getInResponseTo();
s_logger.debug("Received SAMLResponse in response to id=" + responseToId);
SAMLTokenVO token = samlAuthManager.getToken(responseToId);
if (token != null) {
if (!(token.getEntity().equalsIgnoreCase(issuer.getValue()))) {
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "The SAML response contains Issuer Entity ID that is different from the original SAML request", params, responseType));
}
} else {
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Received SAML response for a SSO request that we may not have made or has expired, please try logging in again", params, responseType));
}
// Set IdpId for this session
session.setAttribute(SAMLPluginConstants.SAML_IDPID, issuer.getValue());
Signature sig = processedSAMLResponse.getSignature();
if (idpMetadata.getSigningCertificate() != null && sig != null) {
BasicX509Credential credential = new BasicX509Credential();
credential.setEntityCertificate(idpMetadata.getSigningCertificate());
SignatureValidator validator = new SignatureValidator(credential);
try {
validator.validate(sig);
} catch (ValidationException e) {
s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
}
}
if (username == null) {
username = SAMLUtils.getValueFromAssertions(processedSAMLResponse.getAssertions(), SAML2AuthManager.SAMLUserAttributeName.value());
}
for (Assertion assertion : processedSAMLResponse.getAssertions()) {
if (assertion != null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
break;
}
}
if (idpMetadata.getEncryptionCertificate() != null && spMetadata != null && spMetadata.getKeyPair() != null && spMetadata.getKeyPair().getPrivate() != null) {
Credential credential = SecurityHelper.getSimpleCredential(idpMetadata.getEncryptionCertificate().getPublicKey(), spMetadata.getKeyPair().getPrivate());
StaticKeyInfoCredentialResolver keyInfoResolver = new StaticKeyInfoCredentialResolver(credential);
EncryptedKeyResolver keyResolver = new InlineEncryptedKeyResolver();
Decrypter decrypter = new Decrypter(null, keyInfoResolver, keyResolver);
decrypter.setRootInNewDocument(true);
List<EncryptedAssertion> encryptedAssertions = processedSAMLResponse.getEncryptedAssertions();
if (encryptedAssertions != null) {
for (EncryptedAssertion encryptedAssertion : encryptedAssertions) {
Assertion assertion = null;
try {
assertion = decrypter.decrypt(encryptedAssertion);
} catch (DecryptionException e) {
s_logger.warn("SAML EncryptedAssertion error: " + e.toString());
}
if (assertion == null) {
continue;
}
Signature encSig = assertion.getSignature();
if (idpMetadata.getSigningCertificate() != null && encSig != null) {
BasicX509Credential sigCredential = new BasicX509Credential();
sigCredential.setEntityCertificate(idpMetadata.getSigningCertificate());
SignatureValidator validator = new SignatureValidator(sigCredential);
try {
validator.validate(encSig);
} catch (ValidationException e) {
s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
}
}
if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
}
if (username == null) {
username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());
}
}
}
}
if (username == null) {
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Failed to find admin configured username attribute in the SAML Response. Please ask your administrator to check SAML user attribute name.", params, responseType));
}
UserAccount userAccount = null;
List<UserAccountVO> possibleUserAccounts = userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue());
if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) {
// Users can switch to other allowed accounts later
for (UserAccountVO possibleUserAccount : possibleUserAccounts) {
if (possibleUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
userAccount = possibleUserAccount;
break;
}
}
}
whenFailToAuthenticateThrowExceptionOrRedirectToUrl(params, responseType, resp, issuer, userAccount);
try {
if (apiServer.verifyUser(userAccount.getId())) {
LoginCmdResponse loginResponse = (LoginCmdResponse) apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(), userAccount.getDomainId(), null, remoteAddress, params);
SAMLUtils.setupSamlUserCookies(loginResponse, resp);
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
}
} catch (CloudAuthenticationException | IOException exception) {
s_logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage());
}
}
} catch (IOException e) {
auditTrailSb.append("SP initiated SAML authentication using HTTP redirection failed:");
auditTrailSb.append(e.getMessage());
}
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Unable to authenticate user while performing SAML based SSO. Please make sure your user/account has been added, enable and authorized by the admin before you can authenticate. Please contact your administrator.", params, responseType));
}
use of org.opensaml.saml2.core.Attribute in project cas by apereo.
the class AbstractSaml20ObjectBuilder method newAttribute.
/**
* New attribute.
*
* @param setFriendlyName the set friendly name
* @param e the entry to process and turn into a saml attribute
* @param configuredNameFormats the configured name formats. If an attribute is found in this collection, the linked name format
* will be used.
* @return the attribute
*/
protected Attribute newAttribute(final boolean setFriendlyName, final Map.Entry<String, Object> e, final Map<String, String> configuredNameFormats) {
final Attribute attribute = newSamlObject(Attribute.class);
attribute.setName(e.getKey());
if (setFriendlyName) {
attribute.setFriendlyName(e.getKey());
}
addAttributeValuesToSaml2Attribute(e.getKey(), e.getValue(), attribute.getAttributeValues());
if (!configuredNameFormats.isEmpty() && configuredNameFormats.containsKey(attribute.getName())) {
final String nameFormat = configuredNameFormats.get(attribute.getName());
LOGGER.debug("Found name format [{}] for attribute [{}]", nameFormat, attribute.getName());
switch(nameFormat.trim().toLowerCase()) {
case "basic":
attribute.setNameFormat(Attribute.BASIC);
break;
case "uri":
attribute.setNameFormat(Attribute.URI_REFERENCE);
break;
case "unspecified":
attribute.setNameFormat(Attribute.UNSPECIFIED);
break;
default:
attribute.setNameFormat(nameFormat);
break;
}
LOGGER.debug("Attribute [{}] is assigned the name format of [{}]", attribute.getName(), attribute.getNameFormat());
} else {
LOGGER.debug("Skipped name format, as no name formats are defined or none is found for attribute [{}]", attribute.getName());
}
LOGGER.debug("Attribute [{}] has [{}] value(s)", attribute.getName(), attribute.getAttributeValues().size());
return attribute;
}
Aggregations