use of com.sun.identity.saml2.assertion.Conditions in project OpenAM by OpenRock.
the class IDPSSOUtil method getConditions.
/**
* Returns a <code>SAML Conditions</code> object
*
* @param audienceEntityID the entity id of the audience
* @param effectiveTime the effective time of the assertion
* @return the <code>SAML Conditions</code> object
* @throws SAML2Exception if the operation is not successful
*/
protected static Conditions getConditions(String audienceEntityID, int notBeforeSkewTime, int effectiveTime) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getConditions: ";
Conditions conditions = AssertionFactory.getInstance().createConditions();
Date date = new Date();
date.setTime(date.getTime() - notBeforeSkewTime * 1000);
conditions.setNotBefore(date);
date = new Date();
date.setTime(date.getTime() + effectiveTime * 1000);
conditions.setNotOnOrAfter(date);
List list = new ArrayList();
AudienceRestriction ar = getAudienceRestriction(audienceEntityID);
if (ar == null) {
SAML2Utils.debug.error(classMethod + "Unable to get Audience Restriction");
throw new SAML2Exception(SAML2Utils.bundle.getString("noAudienceRestriction"));
}
list.add(ar);
conditions.setAudienceRestrictions(list);
return conditions;
}
use of com.sun.identity.saml2.assertion.Conditions in project OpenAM by OpenRock.
the class IDPSSOUtil method getAssertion.
/**
* Returns a <code>SAML Assertion</code> object
*
* @throws SAML2Exception if the operation is not successful
* @param request The HTTP request.
* @param session The user's session object.
* @param authnReq The <code>AuthnRequest</code> object.
* @param recipientEntityID The entity ID of the response recipient.
* @param idpEntityID The entity ID of the identity provider.
* @param realm The realm name.
* @param nameIDFormat The <code>NameIDFormat</code>.
* @param acsURL The <code>ACS</code> service <code>url</code>.
* @param affiliationID AffiliationID for IDP initiated SSO.
* @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
* @return the <code>SAML Assertion</code> object.
* @throws SAML2Exception if the operation is not successful.
*/
private static Assertion getAssertion(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getAssertion: ";
Assertion assertion = AssertionFactory.getInstance().createAssertion();
String assertionID = SAML2Utils.generateID();
assertion.setID(assertionID);
assertion.setVersion(SAML2Constants.VERSION_2_0);
assertion.setIssueInstant(new Date());
Issuer issuer = AssertionFactory.getInstance().createIssuer();
issuer.setValue(idpEntityID);
assertion.setIssuer(issuer);
List statementList = new ArrayList();
NewBoolean isNewSessionIndex = new NewBoolean();
AuthnStatement authnStatement = null;
IDPSession idpSession = null;
String sessionIndex = null;
String sessionID = sessionProvider.getSessionID(session);
synchronized (sessionID) {
authnStatement = getAuthnStatement(request, session, isNewSessionIndex, authnReq, idpEntityID, realm, matchingAuthnContext);
if (authnStatement == null) {
return null;
}
sessionIndex = authnStatement.getSessionIndex();
if (isNewSessionIndex.getValue()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "This is a new IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionID);
}
idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
if (idpSession == null) {
idpSession = new IDPSession(session);
}
// Set the metaAlias in the IDP session object
idpSession.setMetaAlias(idpMetaAlias);
IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
}
} else {
idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
}
}
if (isNewSessionIndex.getValue()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "a new IDP session has been saved in cache, " + "with sessionIndex=" + sessionIndex);
}
try {
sessionProvider.addListener(session, sessionListener);
} catch (SessionException e) {
SAML2Utils.debug.error(classMethod + "Unable to add session listener.");
}
} else {
if (idpSession == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// Read from SAML2 Token Repository
IDPSessionCopy idpSessionCopy = null;
try {
idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to obtain IDPSessionCopy from the SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
}
// Copy back to IDPSession
if (idpSessionCopy != null) {
idpSession = new IDPSession(idpSessionCopy);
} else {
SAML2Utils.debug.error("IDPSessionCopy is null");
throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
}
} else if ((idpSession == null) && (!SAML2FailoverUtils.isSAML2FailoverEnabled())) {
SAML2Utils.debug.error("IDPSession is null; SAML2 failover" + "is disabled");
throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "This is an existing IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionProvider.getSessionID(idpSession.getSession()));
}
}
}
statementList.add(authnStatement);
AttributeStatement attrStatement = getAttributeStatement(session, idpEntityID, recipientEntityID, realm);
if (attrStatement != null) {
List attrStatementList = new ArrayList();
attrStatementList.add(attrStatement);
assertion.setAttributeStatements(attrStatementList);
}
// get the assertion effective time (in seconds)
int effectiveTime = getEffectiveTime(realm, idpEntityID);
// get the NotBefore skew (in seconds)
int notBeforeSkewTime = getNotBeforeSkewTime(realm, idpEntityID);
// get the subject element
Subject subject = getSubject(session, authnReq, acsURL, nameIDFormat, realm, idpEntityID, recipientEntityID, effectiveTime, affiliationID);
// register (spEntityID, nameID) with the sso token
// for later logout use
String spEntityID = null;
if (authnReq != null) {
spEntityID = authnReq.getIssuer().getValue();
} else {
spEntityID = recipientEntityID;
}
NameIDandSPpair pair = new NameIDandSPpair(subject.getNameID(), spEntityID);
synchronized (IDPCache.idpSessionsByIndices) {
List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
String id;
if (authnReq != null) {
id = authnReq.getIssuer().getValue();
} else {
id = spEntityID;
}
boolean found = false;
for (NameIDandSPpair nameIDandSPpair : list) {
if (nameIDandSPpair.getSPEntityID().equals(id)) {
found = true;
break;
}
}
if (!found) {
list.add(pair);
}
}
assertion.setAuthnStatements(statementList);
assertion.setSubject(subject);
Conditions conditions = getConditions(recipientEntityID, notBeforeSkewTime, effectiveTime);
assertion.setConditions(conditions);
String discoBootstrapEnabled = getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.DISCO_BOOTSTRAPPING_ENABLED);
if ((discoBootstrapEnabled != null) && discoBootstrapEnabled.equalsIgnoreCase("true")) {
List attrStatementList = assertion.getAttributeStatements();
if (attrStatementList == null) {
attrStatementList = new ArrayList();
assertion.setAttributeStatements(attrStatementList);
}
DiscoveryBootstrap bootstrap = new DiscoveryBootstrap(session, subject, authnStatement.getAuthnContext().getAuthnContextClassRef(), spEntityID, realm);
attrStatementList.add(bootstrap.getBootstrapStatement());
assertion.setAdvice(bootstrap.getCredentials());
}
if (assertionCacheEnabled(realm, idpEntityID)) {
String userName = null;
try {
userName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
}
String cacheKey = userName.toLowerCase();
List assertions = (List) IDPCache.assertionCache.get(cacheKey);
if (assertions == null) {
synchronized (IDPCache.assertionCache) {
assertions = (List) IDPCache.assertionCache.get(cacheKey);
if (assertions == null) {
assertions = new ArrayList();
IDPCache.assertionCache.put(cacheKey, assertions);
}
}
}
synchronized (assertions) {
assertions.add(assertion);
}
IDPCache.assertionByIDCache.put(assertionID, assertion);
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.saveSAML2Token(assertionID, cacheKey, assertion.toXMLString(true, true), conditions.getNotOnOrAfter().getTime() / 1000);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Saving Assertion to SAML2 Token Repository. ID = " + assertionID);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to save Assertion to the SAML2 Token Repository", se);
}
}
}
// Save to SAML2 Token Repository
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
long sessionExpireTime = System.currentTimeMillis() / 1000 + (sessionProvider.getTimeLeft(session));
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), sessionExpireTime);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "SAVE IDPSession!");
}
} catch (SessionException se) {
SAML2Utils.debug.error(classMethod + "Unable to get left-time from the session.", se);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "Unable to save IDPSession to the SAML2 Token Repository", se);
}
return assertion;
}
use of com.sun.identity.saml2.assertion.Conditions in project OpenAM by OpenRock.
the class DefaultConditionsProviderTest method testNoBearer.
@Test
public void testNoBearer() throws TokenCreationException, UnsupportedEncodingException {
Date issueInstant = new Date();
ConditionsProvider conditionsProvider = new DefaultConditionsProvider();
Conditions conditions = conditionsProvider.get(createSAML2Config(), issueInstant, SAML2SubjectConfirmation.HOLDER_OF_KEY);
assertTrue(issueInstant.equals(conditions.getNotBefore()));
assertTrue((issueInstant.getTime() + (TOKEN_LIFETIME_SECONDS * 1000)) == conditions.getNotOnOrAfter().getTime());
}
use of com.sun.identity.saml2.assertion.Conditions in project OpenAM by OpenRock.
the class ConditionsImpl method toXMLString.
/**
* Returns a String representation
* @param includeNSPrefix Determines whether or not the namespace
* qualifier is prepended to the Element when converted
* @param declareNS Determines whether or not the namespace is
* declared within the Element.
* @return A String representation
* @exception SAML2Exception if something is wrong during conversion
*/
public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
StringBuffer sb = new StringBuffer(2000);
String NS = "";
String appendNS = "";
if (declareNS) {
NS = SAML2Constants.ASSERTION_DECLARE_STR;
}
if (includeNSPrefix) {
appendNS = SAML2Constants.ASSERTION_PREFIX;
}
sb.append("<").append(appendNS).append(CONDITIONS_ELEMENT).append(NS);
String str = null;
if (notBefore != null) {
str = DateUtils.toUTCDateFormat(notBefore);
sb.append(" ").append(NOT_BEFORE_ATTR).append("=\"").append(str).append("\"");
}
if (notOnOrAfter != null) {
str = DateUtils.toUTCDateFormat(notOnOrAfter);
sb.append(" ").append(NOT_ON_OR_AFTER_ATTR).append("=\"").append(str).append("\"");
}
sb.append(">\n");
int length = 0;
if (conditions != null) {
length = conditions.size();
for (int i = 0; i < length; i++) {
Condition condition = (Condition) conditions.get(i);
sb.append(condition.toXMLString(includeNSPrefix, false));
}
}
if (audienceRestrictions != null) {
length = audienceRestrictions.size();
for (int i = 0; i < length; i++) {
AudienceRestriction ar = (AudienceRestriction) audienceRestrictions.get(i);
sb.append(ar.toXMLString(includeNSPrefix, false));
}
}
if (oneTimeUses != null) {
length = oneTimeUses.size();
for (int i = 0; i < length; i++) {
OneTimeUse ar = (OneTimeUse) oneTimeUses.get(i);
sb.append(ar.toXMLString(includeNSPrefix, false));
}
}
if (proxyRestrictions != null) {
length = proxyRestrictions.size();
for (int i = 0; i < length; i++) {
ProxyRestriction pr = (ProxyRestriction) proxyRestrictions.get(i);
sb.append(pr.toXMLString(includeNSPrefix, false));
}
}
sb.append("</").append(appendNS).append(CONDITIONS_ELEMENT).append(">\n");
return sb.toString();
}
use of com.sun.identity.saml2.assertion.Conditions in project OpenAM by OpenRock.
the class AssertionImpl method processElement.
private void processElement(Element element) throws SAML2Exception {
if (element == null) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid root element");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_element"));
}
String elemName = element.getLocalName();
if (elemName == null) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): local name missing");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_local_name"));
}
if (!elemName.equals(ASSERTION_ELEMENT)) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid local name " + elemName);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_local_name"));
}
// starts processing attributes
String attrValue = element.getAttribute(ASSERTION_VERSION_ATTR);
if ((attrValue == null) || (attrValue.length() == 0)) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): version missing");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_version"));
}
version = attrValue;
attrValue = element.getAttribute(ASSERTION_ID_ATTR);
if ((attrValue == null) || (attrValue.length() == 0)) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): assertion id missing");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_id"));
}
id = attrValue;
attrValue = element.getAttribute(ASSERTION_ISSUEINSTANT_ATTR);
if ((attrValue == null) || (attrValue.length() == 0)) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): issue instant missing");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_issue_instant"));
}
try {
issueInstant = DateUtils.stringToDate(attrValue);
} catch (ParseException pe) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): invalid issue instant");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalid_date_format"));
}
// starts processing subelements
NodeList nodes = element.getChildNodes();
int numOfNodes = nodes.getLength();
if (numOfNodes < 1) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): assertion has no subelements");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelements"));
}
AssertionFactory factory = AssertionFactory.getInstance();
int nextElem = 0;
Node child = (Node) nodes.item(nextElem);
while (child.getNodeType() != Node.ELEMENT_NODE) {
if (++nextElem >= numOfNodes) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement():" + " assertion has no subelements");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelements"));
}
child = (Node) nodes.item(nextElem);
}
// The first subelement should be <Issuer>
String childName = child.getLocalName();
if ((childName == null) || (!childName.equals(ASSERTION_ISSUER))) {
SAML2SDKUtils.debug.error("AssertionImpl.processElement():" + " the first element is not <Issuer>");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelement_issuer"));
}
issuer = factory.getInstance().createIssuer((Element) child);
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
while (child.getNodeType() != Node.ELEMENT_NODE) {
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
}
// The next subelement may be <ds:Signature>
childName = child.getLocalName();
if ((childName != null) && childName.equals(ASSERTION_SIGNATURE)) {
signature = XMLUtils.print((Element) child);
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
while (child.getNodeType() != Node.ELEMENT_NODE) {
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
}
childName = child.getLocalName();
} else {
signature = null;
}
// The next subelement may be <Subject>
if ((childName != null) && childName.equals(ASSERTION_SUBJECT)) {
subject = factory.createSubject((Element) child);
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
while (child.getNodeType() != Node.ELEMENT_NODE) {
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
}
childName = child.getLocalName();
} else {
subject = null;
}
// The next subelement may be <Conditions>
if ((childName != null) && childName.equals(ASSERTION_CONDITIONS)) {
conditions = factory.createConditions((Element) child);
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
while (child.getNodeType() != Node.ELEMENT_NODE) {
if (++nextElem >= numOfNodes) {
return;
}
child = (Node) nodes.item(nextElem);
}
childName = child.getLocalName();
} else {
conditions = null;
}
// The next subelement may be <Advice>
if ((childName != null) && childName.equals(ASSERTION_ADVICE)) {
advice = factory.createAdvice((Element) child);
nextElem++;
} else {
advice = null;
}
// The next subelements are all statements
while (nextElem < numOfNodes) {
child = (Node) nodes.item(nextElem);
if (child.getNodeType() == Node.ELEMENT_NODE) {
childName = child.getLocalName();
if (childName != null) {
if (childName.equals(ASSERTION_AUTHNSTATEMENT)) {
authnStatements.add(factory.createAuthnStatement((Element) child));
} else if (childName.equals(ASSERTION_AUTHZDECISIONSTATEMENT)) {
authzDecisionStatements.add(factory.createAuthzDecisionStatement((Element) child));
} else if (childName.equals(ASSERTION_ATTRIBUTESTATEMENT)) {
attributeStatements.add(factory.createAttributeStatement((Element) child));
} else if ((childName != null) && childName.equals(ASSERTION_SIGNATURE)) {
signature = XMLUtils.print((Element) child);
} else {
String type = ((Element) child).getAttribute(XSI_TYPE_ATTR);
if (childName.equals(ASSERTION_STATEMENT) && (type != null && type.length() > 0)) {
statements.add(XMLUtils.print((Element) child));
} else {
SAML2SDKUtils.debug.error("AssertionImpl.processElement(): " + "unexpected subelement " + childName);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("unexpected_subelement"));
}
}
}
}
nextElem++;
}
}
Aggregations