use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class Saml2SessionUpgradeHandler method handleSessionUpgrade.
@Override
public void handleSessionUpgrade(InternalSession oldSession, InternalSession newSession) {
final String sessionIndex = oldSession.getProperty(SAML2Constants.IDP_SESSION_INDEX);
if (StringUtils.isNotEmpty(sessionIndex)) {
final String oldSessionID = oldSession.getID().toString();
final String newSessionID = newSession.getID().toString();
final SSOToken oldSSOToken;
final SSOToken newSSOToken;
try {
oldSSOToken = ssoTokenManager.createSSOToken(oldSessionID);
newSSOToken = ssoTokenManager.createSSOToken(newSessionID);
} catch (SSOException ssoe) {
debug.warning("Unable to create an SSOToken for the session ID due to " + ssoe.toString());
return;
}
IDPSession idpSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession == null) {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
final IDPSessionCopy idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
if (idpSessionCopy != null) {
idpSession = new IDPSession(idpSessionCopy);
}
} catch (SAML2TokenRepositoryException stre) {
debug.warning("Unable to retrieve IDPSessionCopy from SAML failover store", stre);
}
}
}
if (idpSession != null) {
idpSession.setSession(newSSOToken);
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
long expirationTime = System.currentTimeMillis() / 1000 + newSession.getTimeLeft();
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), expirationTime);
} catch (SAML2TokenRepositoryException stre) {
debug.error("Failed to update IDPSession in SAML failover store", stre);
}
}
IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
IDPCache.idpSessionsBySessionID.put(newSessionID, idpSession);
}
IDPCache.idpSessionsBySessionID.remove(oldSessionID);
final String partner = IDPCache.spSessionPartnerBySessionID.remove(oldSessionID);
if (partner != null) {
IDPCache.spSessionPartnerBySessionID.put(newSessionID, partner);
}
try {
//We set the sessionIndex to a dummy value so that IDPSessionListener won't try to clear out the caches
//for the still valid sessionIndex.
oldSSOToken.setProperty(SAML2Constants.IDP_SESSION_INDEX, "dummy");
} catch (SSOException ssoe) {
debug.error("Failed to set IDP Session Index for old session", ssoe);
}
}
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class AuthnStatementImpl method parseElement.
// used by the constructors.
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("AuthnStatementImpl.parseElement: " + "Input is null.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
// Make sure this is an AuthnStatement.
if (!SAML2SDKUtils.checkStatement(element, "AuthnStatement")) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("AuthnStatementImpl.parseElement: " + "not AuthnStatement.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
}
// handle the attributes of <AuthnStatement> element
NamedNodeMap atts = ((Node) element).getAttributes();
if (atts != null) {
Node att = atts.getNamedItem("AuthnInstant");
if (att != null) {
try {
authnInstant = DateUtils.stringToDate(((Attr) att).getValue().trim());
} catch (ParseException pe) {
throw new SAML2Exception(pe.getMessage());
}
}
att = atts.getNamedItem("SessionIndex");
if (att != null) {
sessionIndex = ((Attr) att).getValue().trim();
}
att = atts.getNamedItem("SessionNotOnOrAfter");
if (att != null) {
try {
sessionNotOnOrAfter = DateUtils.stringToDate(((Attr) att).getValue().trim());
} catch (ParseException pe) {
throw new SAML2Exception(pe.getMessage());
}
}
}
// handle the sub elementsof the AuthnStatment
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("SubjectLocality")) {
if (subjectLocality != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: included more than one Subject" + "Locality.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (authnContext != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: SubjectLocality is out of " + "sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
subjectLocality = AssertionFactory.getInstance().createSubjectLocality((Element) child);
} else if (childName.equals("AuthnContext")) {
if (authnContext != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: included more than one " + "AuthnContext.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
authnContext = AssertionFactory.getInstance().createAuthnContext((Element) child);
} else {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("AuthnStatementImpl.parse" + "Element: Invalid element:" + childName);
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
}
}
}
validateData();
mutable = false;
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class IDPSSOUtil method getAuthnStatement.
/**
* Returns a <code>SAML AuthnStatement</code> object.
*
* @param request The HTTP request.
* @param session The user's session.
* @param isNewSessionIndex A returned flag from which the caller knows if the session index in the returned
* <code>AuthnStatement</code> is a new session index.
* @param authnReq The <code>AuthnRequest</code> object.
* @param idpEntityID The entity ID of the identity provider.
* @param realm The realm name.
* @param matchingAuthnContext The <code>AuthnContext</code> used to find authentication type and scheme.
* @return The <code>SAML AuthnStatement</code> object.
* @throws SAML2Exception If the operation is not successful.
*/
private static AuthnStatement getAuthnStatement(HttpServletRequest request, Object session, NewBoolean isNewSessionIndex, AuthnRequest authnReq, String idpEntityID, String realm, AuthnContext matchingAuthnContext) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getAuthnStatement: ";
AuthnStatement authnStatement = AssertionFactory.getInstance().createAuthnStatement();
Date authInstant = null;
// will be used when we add SubjectLocality to the statement
try {
String[] values = sessionProvider.getProperty(session, SessionProvider.AUTH_INSTANT);
if (values != null && values.length != 0 && values[0] != null && values[0].length() != 0) {
authInstant = DateUtils.stringToDate(values[0]);
}
} catch (Exception e) {
SAML2Utils.debug.error(classMethod + "exception retrieving info from the session: ", e);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
}
if (authInstant == null) {
authInstant = new Date();
}
authnStatement.setAuthnInstant(authInstant);
AuthnContext authnContext = matchingAuthnContext;
if (authnContext == null) {
String authLevel = null;
try {
String[] values = sessionProvider.getProperty(session, SessionProvider.AUTH_LEVEL);
if (values != null && values.length != 0 && values[0] != null && values[0].length() != 0) {
authLevel = values[0];
}
} catch (Exception e) {
SAML2Utils.debug.error(classMethod + "exception retrieving auth level info from the session: ", e);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
}
IDPAuthnContextMapper idpAuthnContextMapper = getIDPAuthnContextMapper(realm, idpEntityID);
authnContext = idpAuthnContextMapper.getAuthnContextFromAuthLevel(authLevel, realm, idpEntityID);
}
final Response idpResponse = (Response) request.getAttribute(SAML2Constants.SAML_PROXY_IDP_RESPONSE_KEY);
if (idpResponse != null) {
// IdP proxy case: we already received an assertion from the remote IdP and now the IdP proxy is generating
// a new SAML response for the SP.
Set<String> authenticatingAuthorities = new LinkedHashSet<String>();
final List<Assertion> assertions = idpResponse.getAssertion();
for (Assertion assertion : assertions) {
authenticatingAuthorities.addAll(extractAuthenticatingAuthorities(assertion));
}
// According to SAML profile 4.1.4.2 each assertion within the SAML Response MUST have the same issuer, so
// this should suffice. We should have at least one assertion, since the IdP proxy's SP already accepted it.
authenticatingAuthorities.add(assertions.iterator().next().getIssuer().getValue());
authnContext.setAuthenticatingAuthority(new ArrayList<String>(authenticatingAuthorities));
}
authnStatement.setAuthnContext(authnContext);
String sessionIndex = getSessionIndex(session);
if (sessionIndex == null) {
// new sessionIndex
sessionIndex = SAML2Utils.generateIDWithServerID();
try {
String[] values = { sessionIndex };
sessionProvider.setProperty(session, SAML2Constants.IDP_SESSION_INDEX, values);
} catch (SessionException e) {
SAML2Utils.debug.error(classMethod + "error setting session index into the session: ", e);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
}
isNewSessionIndex.setValue(true);
} else {
isNewSessionIndex.setValue(false);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "SessionIndex (in AuthnStatement) =" + sessionIndex);
}
if (sessionIndex != null) {
Set authContextSet = (HashSet) IDPCache.authnContextCache.get(sessionIndex);
if (authContextSet == null || authContextSet.isEmpty()) {
authContextSet = new HashSet();
}
authContextSet.add(authnContext);
// cache the AuthContext to use in the case of session upgrade.
IDPCache.authnContextCache.put(sessionIndex, authContextSet);
authnStatement.setSessionIndex(sessionIndex);
}
return authnStatement;
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class IDPProxyUtil method getSessionPartners.
public static Map getSessionPartners(SOAPMessage message) {
try {
Map sessMap = new HashMap();
Element reqElem = SOAPCommunicator.getInstance().getSamlpElement(message, "LogoutRequest");
LogoutRequest logoutReq = ProtocolFactory.getInstance().createLogoutRequest(reqElem);
List siList = logoutReq.getSessionIndex();
int numSI = 0;
if (siList != null) {
numSI = siList.size();
if (debug.messageEnabled()) {
debug.message("Number of session indices in the logout request is " + numSI);
}
String sessionIndex = (String) siList.get(0);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("getSessionPartners: " + "SessionIndex= " + sessionIndex);
}
IDPSession idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession == null) {
// session is in another server
return sessMap;
}
sessMap.put(SAML2Constants.SESSION_INDEX, sessionIndex);
sessMap.put(SAML2Constants.IDP_SESSION, idpSession);
Object session = idpSession.getSession();
String tokenId = sessionProvider.getSessionID(session);
IDPSession newIdpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenId);
List partners = null;
if (newIdpSession != null) {
partners = newIdpSession.getSessionPartners();
}
if (SAML2Utils.debug.messageEnabled()) {
if (partners != null && !partners.isEmpty()) {
Iterator iter = partners.iterator();
while (iter.hasNext()) {
SAML2SessionPartner partner = (SAML2SessionPartner) iter.next();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SESSION PARTNER's Provider ID: " + partner.getPartner());
}
}
}
}
sessMap.put(SAML2Constants.PARTNERS, partners);
return sessMap;
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("getSessionPartners: Number of " + "session indices in the logout request is null");
}
return null;
}
} catch (SAML2Exception se) {
SAML2Utils.debug.error("getSessionPartners: ", se);
return null;
}
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class AuthnQueryUtil method processAuthnQuery.
/**
* This method processes the <code>AuthnQuery</code> coming
* from a requester.
*
* @param authnQuery the <code>AuthnQuery</code> object
* @param request the <code>HttpServletRequest</code> object
* @param response the <code>HttpServletResponse</code> object
* @param authnAuthorityEntityID entity ID of authentication authority
* @param realm the realm of hosted entity
*
* @return the <code>Response</code> object
* @exception SAML2Exception if the operation is not successful
*/
public static Response processAuthnQuery(AuthnQuery authnQuery, HttpServletRequest request, HttpServletResponse response, String authnAuthorityEntityID, String realm) throws SAML2Exception {
try {
verifyAuthnQuery(authnQuery, authnAuthorityEntityID, realm);
} catch (SAML2Exception se) {
SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery:", se);
return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, null, se.getMessage(), null);
}
Issuer issuer = authnQuery.getIssuer();
String spEntityID = issuer.getValue();
AuthnAuthorityDescriptorElement aad = null;
SAML2MetaManager metaManager = SAML2Utils.getSAML2MetaManager();
try {
aad = metaManager.getAuthnAuthorityDescriptor(realm, authnAuthorityEntityID);
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery:", sme);
return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.RESPONDER, null, SAML2Utils.bundle.getString("metaDataError"), null);
}
if (aad == null) {
return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, null, SAML2Utils.bundle.getString("authnAuthorityNotFound"), null);
}
NameID nameID = getNameID(authnQuery.getSubject(), realm, authnAuthorityEntityID);
if (nameID == null) {
return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null, null);
}
IDPAccountMapper idpAcctMapper = SAML2Utils.getIDPAccountMapper(realm, authnAuthorityEntityID);
String userID = idpAcctMapper.getIdentity(nameID, authnAuthorityEntityID, spEntityID, realm);
if (userID == null) {
return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null, null);
}
IDPAuthnContextMapper idpAuthnContextMapper = IDPSSOUtil.getIDPAuthnContextMapper(realm, authnAuthorityEntityID);
// get assertion for matching authncontext using session
List returnAssertions = new ArrayList();
String qSessionIndex = authnQuery.getSessionIndex();
RequestedAuthnContext requestedAC = authnQuery.getRequestedAuthnContext();
List assertions = null;
String cacheKey = userID.toLowerCase();
AssertionFactory assertionFactory = AssertionFactory.getInstance();
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + "getting user assertions from DB. user = " + cacheKey);
}
List list = null;
try {
list = SAML2FailoverUtils.retrieveSAML2TokensWithSecondaryKey(cacheKey);
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery: " + "Unable to obtain user assertions from CTS Repository. user = " + cacheKey, se);
}
if (list != null && !list.isEmpty()) {
assertions = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
String assertionStr = (String) iter.next();
assertions.add(assertionFactory.createAssertion(assertionStr));
}
}
} else {
assertions = (List) IDPCache.assertionCache.get(cacheKey);
}
if ((assertions != null) && (!assertions.isEmpty())) {
synchronized (assertions) {
for (Iterator aIter = assertions.iterator(); aIter.hasNext(); ) {
Assertion assertion = (Assertion) aIter.next();
if (!assertion.isTimeValid()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + " assertion " + assertion.getID() + " expired.");
}
continue;
}
List authnStmts = assertion.getAuthnStatements();
for (Iterator asIter = authnStmts.iterator(); asIter.hasNext(); ) {
AuthnStatement authnStmt = (AuthnStatement) asIter.next();
AuthnContext authnStmtAC = authnStmt.getAuthnContext();
String sessionIndex = authnStmt.getSessionIndex();
String authnStmtACClassRef = authnStmtAC.getAuthnContextClassRef();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + "authnStmtACClassRef is " + authnStmtACClassRef + ", sessionIndex = " + sessionIndex);
}
if ((qSessionIndex != null) && (qSessionIndex.length() != 0) && (!qSessionIndex.equals(sessionIndex))) {
continue;
}
if (requestedAC != null) {
List requestedACClassRefs = requestedAC.getAuthnContextClassRef();
String comparison = requestedAC.getComparison();
if (idpAuthnContextMapper.isAuthnContextMatching(requestedACClassRefs, authnStmtACClassRef, comparison, realm, authnAuthorityEntityID)) {
returnAssertions.add(assertion);
break;
}
} else {
returnAssertions.add(assertion);
break;
}
}
}
}
// end assertion iterator while.
}
ProtocolFactory protocolFactory = ProtocolFactory.getInstance();
Response samlResp = protocolFactory.createResponse();
if (!returnAssertions.isEmpty()) {
samlResp.setAssertion(returnAssertions);
}
samlResp.setID(SAML2Utils.generateID());
samlResp.setInResponseTo(authnQuery.getID());
samlResp.setVersion(SAML2Constants.VERSION_2_0);
samlResp.setIssueInstant(new Date());
Status status = protocolFactory.createStatus();
StatusCode statusCode = protocolFactory.createStatusCode();
statusCode.setValue(SAML2Constants.SUCCESS);
status.setStatusCode(statusCode);
samlResp.setStatus(status);
Issuer respIssuer = assertionFactory.createIssuer();
respIssuer.setValue(authnAuthorityEntityID);
samlResp.setIssuer(respIssuer);
signResponse(samlResp, authnAuthorityEntityID, realm, false);
return samlResp;
}
Aggregations