use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.
the class DefaultLibrarySPAccountMapper method getAutoFedUser.
/**
* Returns user for the auto federate attribute.
*
* @param realm Realm name.
* @param entityID Hosted <code>EntityID</code>.
* @param assertion <code>Assertion</code> from the identity provider.
* @return Auto federation mapped user from the assertion auto federation <code>AttributeStatement</code>. if the
* statement does not have the auto federation attribute then the NameID value will be used if use NameID as SP user
* ID is enabled, otherwise null.
*/
protected String getAutoFedUser(String realm, String entityID, Assertion assertion, String decryptedNameID, Set<PrivateKey> decryptionKeys) throws SAML2Exception {
if (!isAutoFedEnabled(realm, entityID)) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation is disabled.");
}
return null;
}
String autoFedAttribute = getAttribute(realm, entityID, SAML2Constants.AUTO_FED_ATTRIBUTE);
if (autoFedAttribute == null || autoFedAttribute.isEmpty()) {
debug.error("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation is enabled but the auto federation attribute is not configured.");
return null;
}
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is set to: " + autoFedAttribute);
}
Set<String> autoFedAttributeValue = null;
List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
if (attributeStatements == null || attributeStatements.isEmpty()) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Assertion does not have any attribute statements.");
}
} else {
for (AttributeStatement statement : attributeStatements) {
autoFedAttributeValue = getAttribute(statement, autoFedAttribute, decryptionKeys);
if (autoFedAttributeValue != null && !autoFedAttributeValue.isEmpty()) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Found auto federation attribute value in Assertion: " + autoFedAttributeValue);
}
break;
}
}
}
if (autoFedAttributeValue == null || autoFedAttributeValue.isEmpty()) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is not specified" + " as an attribute.");
}
if (!useNameIDAsSPUserID(realm, entityID)) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: NameID as SP UserID was not enabled " + " and auto federation attribute " + autoFedAttribute + " was not found in the Assertion");
}
return null;
} else {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Trying now to autofederate with nameID" + ", nameID =" + decryptedNameID);
}
autoFedAttributeValue = CollectionUtils.asSet(decryptedNameID);
}
}
String autoFedMapAttribute = null;
DefaultSPAttributeMapper attributeMapper = new DefaultSPAttributeMapper();
Map<String, String> attributeMap = attributeMapper.getConfigAttributeMap(realm, entityID, SP);
if (attributeMap == null || attributeMap.isEmpty()) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: attribute map is not configured.");
}
} else {
autoFedMapAttribute = attributeMap.get(autoFedAttribute);
}
if (autoFedMapAttribute == null) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation attribute map is not specified in config.");
}
// assume it is the same as the auto fed attribute name
autoFedMapAttribute = autoFedAttribute;
}
try {
Map<String, Set<String>> map = new HashMap<>(1);
map.put(autoFedMapAttribute, autoFedAttributeValue);
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Search map: " + map);
}
String userId = dsProvider.getUserID(realm, map);
if (userId != null && !userId.isEmpty()) {
return userId;
} else {
// return auto-federation attribute value as uid
if (isDynamicalOrIgnoredProfile(realm)) {
if (debug.messageEnabled()) {
debug.message("DefaultLibrarySPAccountMapper: dynamical user creation or ignore profile " + "enabled : uid=" + autoFedAttributeValue);
}
// return the first value as uid
return autoFedAttributeValue.iterator().next();
}
}
} catch (DataStoreProviderException dse) {
if (debug.warningEnabled()) {
debug.warning("DefaultLibrarySPAccountMapper.getAutoFedUser: Datastore provider exception", dse);
}
}
return null;
}
use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.
the class AssertionIDRequestUtil method sendAssertionIDRequestURI.
/**
* Sends the Assertion ID to specifiied Assertion ID Request Service and
* returns <code>Assertion</code> coming from the Assertion ID Request
* Service.
*
* @param assertionID the asssertionID</code> object
* @param samlAuthorityEntityID entity ID of SAML authority
* @param role SAML authority role, for example,
* <code>SAML2Constants.ATTR_AUTH_ROLE</code>,
* <code>SAML2Constants.AUTHN_AUTH_ROLE</code> or
* <code>SAML2Constants.IDP_ROLE</code>
* @param realm the realm of hosted entity
*
* @return the <code>Assertion</code> object
* @exception SAML2Exception if the operation is not successful
*
* @supported.api
*/
public static Assertion sendAssertionIDRequestURI(String assertionID, String samlAuthorityEntityID, String role, String realm) throws SAML2Exception {
StringBuffer locationSB = new StringBuffer();
getRoleDescriptorAndLocation(samlAuthorityEntityID, role, realm, SAML2Constants.URI, locationSB);
if (locationSB.indexOf("?") == -1) {
locationSB.append("?");
} else {
locationSB.append("&");
}
locationSB.append("ID=").append(assertionID);
String location = fillInBasicAuthInfo(locationSB.toString(), realm, samlAuthorityEntityID, role);
URL url = null;
try {
url = new URL(location);
} catch (MalformedURLException me) {
throw new SAML2Exception(me.getMessage());
}
try {
HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
conn.setInstanceFollowRedirects(false);
conn.setUseCaches(false);
conn.setDoOutput(false);
conn.connect();
int respCode = conn.getResponseCode();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Response code = " + respCode + ", Response message = " + conn.getResponseMessage());
}
if (respCode != HttpURLConnection.HTTP_OK) {
return null;
}
String contentType = conn.getContentType();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Content type = " + contentType);
}
if ((contentType == null) || (contentType.indexOf(MIME_TYPE_ASSERTION) == -1)) {
return null;
}
int contentLength = conn.getContentLength();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AssertionIDRequestUtil.sendAssertionIDRequestURI: " + "Content length = " + contentLength);
}
BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());
StringBuffer contentSB = new StringBuffer();
byte[] content = new byte[2048];
if (contentLength != -1) {
int read = 0, totalRead = 0;
int left;
while (totalRead < contentLength) {
left = contentLength - totalRead;
read = bin.read(content, 0, left < content.length ? left : content.length);
if (read == -1) {
// We need to close connection !!
break;
} else {
if (read > 0) {
totalRead += read;
contentSB.append(new String(content, 0, read));
}
}
}
} else {
int numbytes;
int totalRead = 0;
while (true) {
numbytes = bin.read(content);
if (numbytes == -1) {
break;
}
totalRead += numbytes;
contentSB.append(new String(content, 0, numbytes));
}
}
return AssertionFactory.getInstance().createAssertion(contentSB.toString());
} catch (IOException ioex) {
SAML2Utils.debug.error("AssertionIDRequest.sendAssertionIDRequestURI:", ioex);
throw new SAML2Exception(ioex.getMessage());
}
}
use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.
the class ResponseImpl method parseElement.
private void parseElement(Element element) throws SAML2Exception {
// make sure that the input xml block is not null
if (element == null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parseElement: " + "element input is null.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
// Make sure this is an Response.
String tag = null;
tag = element.getLocalName();
if ((tag == null) || (!tag.equals("Response"))) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parseElement: " + "not Response.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
}
// handle the attributes of <Response> element
NamedNodeMap atts = ((Node) element).getAttributes();
if (atts != null) {
int length = atts.getLength();
for (int i = 0; i < length; i++) {
Attr attr = (Attr) atts.item(i);
String attrName = attr.getName();
String attrValue = attr.getValue().trim();
if (attrName.equals("ID")) {
responseId = attrValue;
} else if (attrName.equals("InResponseTo")) {
inResponseTo = attrValue;
} else if (attrName.equals("Version")) {
version = attrValue;
} else if (attrName.equals("IssueInstant")) {
try {
issueInstant = DateUtils.stringToDate(attrValue);
} catch (ParseException pe) {
throw new SAML2Exception(pe.getMessage());
}
} else if (attrName.equals("Destination")) {
destination = attrValue;
} else if (attrName.equals("Consent")) {
consent = attrValue;
}
}
}
// handle child elements
NodeList nl = element.getChildNodes();
Node child;
String childName;
int length = nl.getLength();
for (int i = 0; i < length; i++) {
child = nl.item(i);
if ((childName = child.getLocalName()) != null) {
if (childName.equals("Issuer")) {
if (issuer != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: included more than one Issuer.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (signatureString != null || extensions != null || status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
issuer = AssertionFactory.getInstance().createIssuer((Element) child);
} else if (childName.equals("Signature")) {
if (signatureString != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:included more than one Signature.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (extensions != null || status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
signatureString = XMLUtils.print((Element) child, "UTF-8");
isSigned = true;
} else if (childName.equals("Extensions")) {
if (extensions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:included more than one Extensions.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
extensions = ProtocolFactory.getInstance().createExtensions((Element) child);
} else if (childName.equals("Status")) {
if (status != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: included more than one Status.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
status = ProtocolFactory.getInstance().createStatus((Element) child);
} else if (childName.equals("Assertion")) {
if (assertions == null) {
assertions = new ArrayList();
}
Element canoEle = SAMLUtils.getCanonicalElement(child);
if (canoEle == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorCanonical"));
}
assertions.add(AssertionFactory.getInstance().createAssertion(canoEle));
} else if (childName.equals("EncryptedAssertion")) {
if (encAssertions == null) {
encAssertions = new ArrayList();
}
encAssertions.add(AssertionFactory.getInstance().createEncryptedAssertion((Element) child));
} else {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: Invalid element:" + childName);
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
}
}
}
super.validateData();
if (assertions != null) {
Iterator iter = assertions.iterator();
while (iter.hasNext()) {
((Assertion) iter.next()).makeImmutable();
}
assertions = Collections.unmodifiableList(assertions);
}
if (encAssertions != null) {
encAssertions = Collections.unmodifiableList(encAssertions);
}
isMutable = false;
}
use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.
the class SAML2Proxy method getUrl.
private static String getUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (request == null || response == null) {
DEBUG.error("SAML2Proxy: Null request or response");
return getUrlWithError(request, BAD_REQUEST);
}
try {
SAMLUtils.checkHTTPContentLength(request);
} catch (ServletException se) {
DEBUG.error("SAML2Proxy: content length too large");
return getUrlWithError(request, BAD_REQUEST);
}
if (FSUtils.needSetLBCookieAndRedirect(request, response, false)) {
return getUrlWithError(request, MISSING_COOKIE);
}
// get entity id and orgName
String requestURL = request.getRequestURL().toString();
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
SAML2MetaManager metaManager = SAML2Utils.getSAML2MetaManager();
String hostEntityId;
if (metaManager == null) {
DEBUG.error("SAML2Proxy: Unable to obtain metaManager");
return getUrlWithError(request, MISSING_META_MANAGER);
}
try {
hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
if (hostEntityId == null) {
throw new SAML2MetaException("Caught Instantly");
}
} catch (SAML2MetaException sme) {
DEBUG.warning("SAML2Proxy: unable to find hosted entity with metaAlias: {} Exception: {}", metaAlias, sme.toString());
return getUrlWithError(request, META_DATA_ERROR);
}
String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
if (StringUtils.isEmpty(realm)) {
realm = "/";
}
ResponseInfo respInfo;
try {
respInfo = SPACSUtils.getResponse(request, response, realm, hostEntityId, metaManager);
} catch (SAML2Exception se) {
DEBUG.error("SAML2Proxy: Unable to obtain SAML response", se);
return getUrlWithError(request, SAML_GET_RESPONSE_ERROR, se.getL10NMessage(request.getLocale()));
}
Map smap;
try {
// check Response/Assertion and get back a Map of relevant data
smap = SAML2Utils.verifyResponse(request, response, respInfo.getResponse(), realm, hostEntityId, respInfo.getProfileBinding());
} catch (SAML2Exception se) {
DEBUG.error("SAML2Proxy: An error occurred while verifying the SAML response", se);
return getUrlWithError(request, SAML_VERIFY_RESPONSE_ERROR, se.getL10NMessage(request.getLocale()));
}
String key = generateKey();
//survival time is one hour
SAML2ResponseData data = new SAML2ResponseData((String) smap.get(SAML2Constants.SESSION_INDEX), (Subject) smap.get(SAML2Constants.SUBJECT), (Assertion) smap.get(SAML2Constants.POST_ASSERTION), respInfo);
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
//counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, data, sessionExpireTime);
} catch (SAML2TokenRepositoryException e) {
DEBUG.error("An error occurred while persisting the SAML token", e);
return getUrlWithError(request, SAML_FAILOVER_DISABLED_ERROR);
}
} else {
SAML2Store.saveTokenWithKey(key, data);
}
return getUrlWithKey(request, key);
}
use of com.sun.identity.saml2.assertion.Assertion in project OpenAM by OpenRock.
the class SAML2 method linkAttributeValues.
/**
* Performs the functions of linking attribute values that have been received from the assertion
* by building them into appropriate strings and asking the auth service to migrate them into session
* properties once authentication is completed.
*/
private void linkAttributeValues(Assertion assertion, String userName) throws AuthLoginException, SAML2Exception {
final String spName = metaManager.getEntityByMetaAlias(metaAlias);
final SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, spName);
final String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
final boolean needAttributeEncrypted = SPACSUtils.getNeedAttributeEncrypted(assertionEncryptedAttr, spssoconfig);
final Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
final List<Attribute> attrs = SPACSUtils.getAttrs(assertion, needAttributeEncrypted, decryptionKeys);
final SPAttributeMapper attrMapper = SAML2Utils.getSPAttributeMapper(realm, spName);
final Map<String, Set<String>> attrMap;
try {
attrMap = attrMapper.getAttributes(attrs, userName, spName, entityName, realm);
} catch (SAML2Exception se) {
//no attributes
return;
}
setUserAttributes(attrMap);
if (assertion.getAdvice() != null) {
List<String> creds = assertion.getAdvice().getAdditionalInfo();
attrMap.put(SAML2Constants.DISCOVERY_BOOTSTRAP_CREDENTIALS, new HashSet<>(creds));
}
for (String name : attrMap.keySet()) {
Set<String> value = attrMap.get(name);
StringBuilder toStore = new StringBuilder();
// | is defined as the property value delimiter, cf FMSessionProvider#setProperty
for (String toAdd : value) {
toStore.append(com.sun.identity.shared.StringUtils.getEscapedValue(toAdd)).append(PROPERTY_VALUES_SEPARATOR);
}
toStore.deleteCharAt(toStore.length() - 1);
setUserSessionProperty(name, toStore.toString());
}
}
Aggregations