use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method getACSurlFromMetaByIndex.
/**
* Returns the assertion consumer service <code>URL</code> from
* meta data by binding
*
* @param spEntityID the entity id of the service provider
* @param realm the realm name of the identity provider
* @param acsIndex the <code>ACS</code> index
* @param returnedBinding the binding used to send back
* <code>Response</code>
* @return the assertion consumer service <code>URL</code>
* @throws SAML2Exception if the operation is not successful
*/
public static String getACSurlFromMetaByIndex(String spEntityID, String realm, int acsIndex, StringBuffer returnedBinding) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getACSurlFromMetaByIndex: ";
SPSSODescriptorElement spSSODescriptorElement = getSPSSODescriptor(realm, spEntityID, classMethod);
List acsList = spSSODescriptorElement.getAssertionConsumerService();
int index;
String acsURL = null;
String binding = null;
String defaultAcsURL = null;
String defaultBinding = null;
String firstAcsURL = null;
String firstBinding = null;
AssertionConsumerServiceElement acs = null;
for (int i = 0; i < acsList.size(); i++) {
acs = (AssertionConsumerServiceElement) acsList.get(i);
index = acs.getIndex();
binding = acs.getBinding();
if (index == acsIndex) {
acsURL = acs.getLocation();
binding = acs.getBinding();
break;
}
if (acs.isIsDefault()) {
defaultAcsURL = acs.getLocation();
defaultBinding = acs.getBinding();
}
if (i == 0) {
firstAcsURL = acs.getLocation();
firstBinding = acs.getBinding();
}
}
if (acsURL == null || acsURL.length() == 0) {
acsURL = defaultAcsURL;
if (acsURL == null || acsURL.length() == 0) {
acsURL = firstAcsURL;
if (acsURL == null || acsURL.length() == 0) {
acsURL = null;
SAML2Utils.debug.error(classMethod + "Unable to get valid Assertion " + "Consumer Service URL");
return null;
}
returnedBinding.append(firstBinding);
} else {
returnedBinding.append(defaultBinding);
}
} else {
returnedBinding.append(binding);
}
return acsURL;
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class IDPSSOUtil method sendNoPassiveResponse.
/**
* A convenience method to construct NoPassive SAML error responses for SAML passive authentication requests.
*
* @param request The servlet request.
* @param response The servlet response.
* @param out The print writer for writing out presentation.
* @param idpMetaAlias The IdP's metaAlias.
* @param idpEntityID The IdP's entity ID.
* @param realm The realm where the IdP belongs to.
* @param authnReq The SAML AuthnRequest sent by the SP.
* @param relayState The RelayState value.
* @param spEntityID The SP's entity ID.
* @throws SAML2Exception If there was an error while creating or sending the response back to the SP.
*/
public static void sendNoPassiveResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String idpMetaAlias, String idpEntityID, String realm, AuthnRequest authnReq, String relayState, String spEntityID) throws SAML2Exception {
Response res = SAML2Utils.getErrorResponse(authnReq, SAML2Constants.RESPONDER, SAML2Constants.NOPASSIVE, null, idpEntityID);
StringBuffer returnedBinding = new StringBuffer();
String acsURL = IDPSSOUtil.getACSurl(spEntityID, realm, authnReq, request, returnedBinding);
String acsBinding = returnedBinding.toString();
sendResponse(request, response, out, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, null);
}
use of com.sun.identity.saml2.protocol.Response 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.protocol.Response in project OpenAM by OpenRock.
the class DoManageNameID method processHttpRequest.
/**
* Parses the request parameters and process the ManageNameID
* Request from the remote entity.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param paramsMap Map of all other parameters.
* @throws SAML2Exception if error occurred while processing the request.
* @throws SessionException if error processing the request from remote entity.
* @throws ServletException if request length is invalid.
*/
public static void processHttpRequest(HttpServletRequest request, HttpServletResponse response, Map paramsMap) throws SAML2Exception, SessionException, ServletException {
String method = "processHttpRequest: ";
String metaAlias = null;
String remoteEntityID = null;
String queryString = null;
// handle DOS attack
SAMLUtils.checkHTTPContentLength(request);
String requestURL = request.getRequestURI();
metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
if (metaAlias == null) {
logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
throw new SAML2Exception(SAML2Utils.bundle.getString("MetaAliasNotFound"));
}
String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
String hostEntity = metaManager.getEntityByMetaAlias(metaAlias);
String hostRole = SAML2Utils.getHostEntityRole(paramsMap);
boolean isSupported = false;
if (SAML2Constants.IDP_ROLE.equals(hostRole)) {
isSupported = SAML2Utils.isIDPProfileBindingSupported(realm, hostEntity, SAML2Constants.MNI_SERVICE, SAML2Constants.HTTP_REDIRECT);
} else {
isSupported = SAML2Utils.isSPProfileBindingSupported(realm, hostEntity, SAML2Constants.MNI_SERVICE, SAML2Constants.HTTP_REDIRECT);
}
if (!isSupported) {
debug.error(method + "MNI binding: Redirect is not supported for " + hostEntity);
String[] data = { hostEntity, SAML2Constants.HTTP_REDIRECT };
LogUtil.error(Level.INFO, LogUtil.BINDING_NOT_SUPPORTED, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
// Retrieve ManageNameIDRequest
ManageNameIDRequest mniRequest = getMNIRequest(request);
remoteEntityID = mniRequest.getIssuer().getValue();
if (remoteEntityID == null) {
logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, remoteEntityID);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
}
boolean needToVerify = SAML2Utils.getWantMNIRequestSigned(realm, hostEntity, hostRole);
if (needToVerify) {
queryString = request.getQueryString();
boolean valid = SAML2Utils.verifyQueryString(queryString, realm, hostRole, remoteEntityID);
if (!valid) {
logError("invalidSignInRequest", LogUtil.MNI_REQUEST_INVALID_SIGNATURE, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
}
String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
if (debug.messageEnabled()) {
debug.message(method + "Meta Alias is : " + metaAlias);
debug.message(method + "Remote EntityID is : " + remoteEntityID);
debug.message(method + "Host Entity role is : " + hostRole);
debug.message(method + "Relay state is : " + relayState);
}
try {
ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostRole, SAML2Constants.HTTP_REDIRECT);
String mniURL = mniService.getResponseLocation();
if (mniURL == null) {
mniURL = mniService.getLocation();
}
ManageNameIDResponse mniResponse = processManageNameIDRequest(mniRequest, metaAlias, remoteEntityID, paramsMap, mniURL, SAML2Constants.HTTP_REDIRECT, request, response);
sendMNIResponse(response, mniResponse, mniURL, relayState, realm, hostEntity, hostRole, remoteEntityID);
} catch (SAML2MetaException e) {
logError("metaDataError", LogUtil.METADATA_ERROR, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
use of com.sun.identity.saml2.protocol.Response in project OpenAM by OpenRock.
the class DoManageNameID method processSOAPRequest.
/**
* Parses the request parameters and process the ManageNameID
* Request from the remote entity.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param paramsMap Map of all other parameters.
* @throws SAML2Exception if error occurred while processing the request.
* @throws IOException if error generation DOM from input stream.
* @throws SOAPException if error generating soap message.
* @throws ServletException if request length is invalid.
*/
public static void processSOAPRequest(HttpServletRequest request, HttpServletResponse response, Map paramsMap) throws SAML2Exception, IOException, SOAPException, ServletException {
String method = "processSOAPRequest: ";
String metaAlias = null;
String remoteEntityID = null;
String requestURL = request.getRequestURI();
String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
// handle DOS attack
SAMLUtils.checkHTTPContentLength(request);
metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
if (metaAlias == null) {
logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
throw new SAML2Exception(SAML2Utils.bundle.getString("MetaAliasNotFound"));
}
String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
String hostEntity = metaManager.getEntityByMetaAlias(metaAlias);
boolean isSupported = false;
if (SAML2Constants.IDP_ROLE.equals(hostEntityRole)) {
isSupported = SAML2Utils.isIDPProfileBindingSupported(realm, hostEntity, SAML2Constants.MNI_SERVICE, SAML2Constants.SOAP);
} else {
isSupported = SAML2Utils.isSPProfileBindingSupported(realm, hostEntity, SAML2Constants.MNI_SERVICE, SAML2Constants.SOAP);
}
if (!isSupported) {
debug.error(method + "MNI binding: SOAP is not supported for " + hostEntity);
String[] data = { hostEntity, SAML2Constants.SOAP };
LogUtil.error(Level.INFO, LogUtil.BINDING_NOT_SUPPORTED, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
}
// Retrieve a SOAPMessage
SOAPMessage message = SOAPCommunicator.getInstance().getSOAPMessage(request);
ManageNameIDRequest mniRequest = getMNIRequest(message);
remoteEntityID = mniRequest.getIssuer().getValue();
if (remoteEntityID == null) {
logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, metaAlias);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
}
if (debug.messageEnabled()) {
debug.message(method + "Meta Alias is : " + metaAlias);
debug.message(method + "Host EntityID is : " + hostEntity);
debug.message(method + "Remote EntityID is : " + remoteEntityID);
}
String dest = mniRequest.getDestination();
boolean valid = verifyMNIRequest(mniRequest, realm, remoteEntityID, hostEntity, hostEntityRole, dest);
if (!valid) {
logError("invalidSignInRequest", LogUtil.MNI_REQUEST_INVALID_SIGNATURE, metaAlias);
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
ManageNameIDResponse mniResponse = processManageNameIDRequest(mniRequest, metaAlias, remoteEntityID, paramsMap, null, SAML2Constants.SOAP, request, response);
signMNIResponse(mniResponse, realm, hostEntity, hostEntityRole, remoteEntityID);
SOAPMessage reply = SOAPCommunicator.getInstance().createSOAPMessage(mniResponse.toXMLString(true, true), false);
if (reply != null) {
/* Need to call saveChanges because we're
* going to use the MimeHeaders to set HTTP
* response information. These MimeHeaders
* are generated as part of the save. */
if (reply.saveRequired()) {
reply.saveChanges();
}
response.setStatus(HttpServletResponse.SC_OK);
SAML2Utils.putHeaders(reply.getMimeHeaders(), response);
// Write out the message on the response stream
OutputStream os = response.getOutputStream();
reply.writeTo(os);
os.flush();
} else {
logError("errorObtainResponse", LogUtil.CANNOT_INSTANTIATE_MNI_RESPONSE, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorObtainResponse"));
}
}
Aggregations