use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.
the class JSONSerialisationTest method complexInternalSessionSerializationWorks.
@Test(dataProvider = "complex")
public void complexInternalSessionSerializationWorks(String path) throws Exception {
InternalSession is = serialization.deserialise(getJSON(path), InternalSession.class);
assertThat(is).isNotNull();
String serialised = serialization.serialise(is);
assertThat(serialised).isNotNull().isNotEmpty();
InternalSession is2 = serialization.deserialise(serialised, InternalSession.class);
assertThat(is2).isNotNull().isNotSameAs(is);
assertThat(is.getID()).isEqualTo(is2.getID());
}
use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.
the class JSONSerialisationTest method tokenRestrictionDeserialisationWithTypeWorks.
@Test
public void tokenRestrictionDeserialisationWithTypeWorks() throws Exception {
InternalSession is = serialization.deserialise(getJSON("/json/basic-session-with-restriction.json"), InternalSession.class);
assertThat(is).isNotNull();
TokenRestriction restriction = is.getRestrictionForToken(new SessionID("AQIC5wM2LY4SfcyTLz6VjQ7nkFeDcEh8K5dXkIE" + "NpXlpg28.*AAJTSQACMDIAAlMxAAIwMQACU0sAEzc5ODIzMDM5MzQyNzU2MTg1NDQ.*"));
assertThat(restriction).isNotNull().isInstanceOf(DNOrIPAddressListTokenRestriction.class);
assertThat(restriction.toString().equals("Fzy2GsI/O1TsXhvlVuqjqIuTG2k="));
assertThat(is.getSessionHandle()).isNotNull().isEqualTo("shandle:weasel");
}
use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.
the class Adaptive method process.
@Override
public int process(Callback[] callbacks, int state) throws AuthLoginException {
int currentScore = 0;
debug.message("{}: process called with state = {}", ADAPTIVE, state);
if (state != ISAuthConstants.LOGIN_START) {
throw new AuthLoginException("Authentication failed: Internal Error - NOT LOGIN_START");
}
if (userName == null || userName.length() == 0) {
// session
try {
SSOTokenManager mgr = SSOTokenManager.getInstance();
InternalSession isess = getLoginState(ADAPTIVE).getOldSession();
if (isess == null) {
throw new AuthLoginException(ADAPTIVE, "noInternalSession", null);
}
SSOToken token = mgr.createSSOToken(isess.getID().toString());
userUUID = token.getPrincipal().getName();
userName = token.getProperty("UserToken");
if (debug.messageEnabled()) {
debug.message("{}.process() : UserName '{}' in SSOToken", ADAPTIVE, userName);
}
if (userName == null || userName.length() == 0) {
throw new AuthLoginException("amAuth", "noUserName", null);
}
} catch (SSOException e) {
debug.message("{}: amAuthIdentity NULL ", ADAPTIVE);
throw new AuthLoginException(ADAPTIVE, "noIdentity", null);
}
}
if (debug.messageEnabled()) {
debug.message("{}: Login Attempt Username = {}", ADAPTIVE, userName);
}
amAuthIdentity = getIdentity();
clientIP = ClientUtils.getClientIPAddress(getHttpServletRequest());
if (amAuthIdentity == null) {
throw new AuthLoginException(ADAPTIVE, "noIdentity", null);
}
try {
if (IPRangeCheck) {
int retVal = checkIPRange();
if (debug.messageEnabled()) {
debug.message("{}.checkIPRange: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (IPHistoryCheck) {
int retVal = checkIPHistory();
if (debug.messageEnabled()) {
debug.message("{}.checkIPHistory: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (knownCookieCheck) {
int retVal = checkKnownCookie();
if (debug.messageEnabled()) {
debug.message("{}.checkKnownCookie: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (timeOfDayCheck) {
int retVal = checkTimeDay();
if (debug.messageEnabled()) {
debug.message("{}.checkTimeDay: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (timeSinceLastLoginCheck) {
int retVal = checkLastLogin();
if (debug.messageEnabled()) {
debug.message("{}.checkLastLogin: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (riskAttributeCheck) {
int retVal = checkRiskAttribute();
if (debug.messageEnabled()) {
debug.message("{}.checkRiskAttribute: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (authFailureCheck) {
int retVal = checkAuthFailure();
if (debug.messageEnabled()) {
debug.message("{}.checkAuthFailure: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (deviceCookieCheck) {
int retVal = checkRegisteredClient();
if (debug.messageEnabled()) {
debug.message("{}.checkRegisteredClient: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (geoLocationCheck) {
int retVal = checkGeoLocation();
if (debug.messageEnabled()) {
debug.message("{}.checkGeoLocation: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
if (reqHeaderCheck) {
int retVal = checkRequestHeader();
if (debug.messageEnabled()) {
debug.message("{}.checkRequestHeader: returns {}", ADAPTIVE, retVal);
}
currentScore += retVal;
}
} catch (Exception ex) {
currentScore = Integer.MAX_VALUE;
debug.error("{}.process() : Unknown exception occurred while executing checks, module will fail.", ADAPTIVE, ex);
}
setPostAuthNParams();
if (currentScore < adaptiveThreshold) {
if (debug.messageEnabled()) {
debug.message("{}: Returning Success. Username='{}'", ADAPTIVE, userName);
}
return ISAuthConstants.LOGIN_SUCCEED;
} else {
if (debug.messageEnabled()) {
debug.message("{}: Returning Fail. Username='{}'", ADAPTIVE, userName);
}
throw new AuthLoginException(ADAPTIVE + " - Risk determined.");
}
}
use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.
the class LoginViewBean method forwardTo.
/**
* Forwards the request to this view bean, displaying the page. This
* method is the equivalent of <code>RequestDispatcher.forward()</code>,
* meaning that the same semantics apply to the use of this method.
* This method makes implicit use of the display URL returned
* by the <code>getDisplayURL()</code> method.
* @param requestContext servlet context for auth request
*/
public void forwardTo(RequestContext requestContext) {
loginDebug.message("In forwardTo()");
SSOToken ssoToken = null;
if (requestContext != null) {
request = requestContext.getRequest();
response = requestContext.getResponse();
}
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
if (AuthClientUtils.isVersionHeaderEnabled()) {
response.setHeader("X-DSAMEVersion", AuthClientUtils.getDSAMEVersion());
}
// get request ( GET ) parameters for 'login' process
reqDataHash = AuthUtils.parseRequestParameters(request);
/*if (loginDebug.messageEnabled()) {
loginDebug.message("request data hash : " + reqDataHash);
}*/
client_type = AuthUtils.getClientType(request);
// Set header for Misrouted server's usage
response.setHeader("AM_CLIENT_TYPE", client_type);
if (loginDebug.messageEnabled()) {
loginDebug.message("Client Type is: " + client_type);
loginDebug.message("Request method is : " + request.getMethod());
}
if (request.getMethod().equalsIgnoreCase("POST")) {
isPost = true;
}
SessionID sessionID = null;
InternalSession intSession = null;
try {
boolean isBackPost = false;
// if the request is a GET then iPlanetAMDirectoryPro cookie
// will be used to retrieve the session for session upgrade
sessionID = AuthUtils.getSessionIDFromRequest(request);
ssoToken = AuthUtils.getExistingValidSSOToken(sessionID);
//Check for session Timeout
if ((ssoToken == null) && (sessionID != null) && (sessionID.toString().length() != 0)) {
if (AuthUtils.isTimedOut(sessionID)) {
clearCookie(request);
errorCode = AMAuthErrorCode.AUTH_TIMEOUT;
ErrorMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_TIMEOUT, AuthUtils.ERROR_MESSAGE);
errorTemplate = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_TIMEOUT, AuthUtils.ERROR_TEMPLATE);
ISLocaleContext localeContext = new ISLocaleContext();
localeContext.setLocale(request);
java.util.Locale locale = localeContext.getLocale();
rb = rbCache.getResBundle(bundleName, locale);
super.forwardTo(requestContext);
return;
}
}
forceAuth = AuthUtils.forceAuthFlagExists(reqDataHash);
if (ssoToken != null) {
if (AuthUtils.newSessionArgExists(reqDataHash)) {
SSOTokenManager.getInstance().destroyToken(ssoToken);
} else {
loginDebug.message("Old Session is Active.");
newOrgExist = checkNewOrg(ssoToken);
if (newOrg) {
sessionID = new SessionID();
}
if (!newOrgExist) {
if (isPost) {
isBackPost = canGetOrigCredentials(ssoToken);
}
if (forceAuth) {
sessionUpgrade = true;
} else {
sessionUpgrade = AuthUtils.checkSessionUpgrade(ssoToken, reqDataHash);
}
if (loginDebug.messageEnabled()) {
loginDebug.message("Session Upgrade = " + sessionUpgrade);
}
}
}
}
if ("true".equals(request.getParameter("new_org"))) {
ssoToken = AuthUtils.getExistingValidSSOToken(new SessionID(request));
handleNewOrgResponse(ssoToken);
if (logIntoDiffOrg) {
//session is already deleted, so we should just continue our login process
newOrgExist = true;
} else {
ac = AuthUtils.getAuthContext(request, response, sessionID, sessionUpgrade, isBackPost);
clearCookieAndDestroySession(ac);
}
}
if ((ssoToken != null) && !sessionUpgrade && !newOrgExist) {
try {
loginDebug.message("Session is Valid / already " + "authenticated");
bValidSession = true;
/*
* redirect to 'goto' parameter or SPI hook or default
* redirect URL.
*/
if (request != null) {
redirect_url = AuthUtils.getValidGotoURL(request, ssoToken.getProperty("Organization"));
if ((redirect_url == null) || (redirect_url.length() == 0)) {
redirect_url = ssoToken.getProperty(ISAuthConstants.SUCCESS_URL);
}
}
if (redirect_url == null) {
ResultVal = rb.getString("authentication.already.login");
}
LoginSuccess = true;
boolean doForward = AuthUtils.forwardSuccessExists(request);
if (doForward || (redirect_url != null && (redirect_url.startsWith(SSO_REDIRECT) || redirect_url.startsWith(SSO_POST)))) {
if (loginDebug.messageEnabled()) {
loginDebug.message("LoginViewBean.forwardRequest=true");
loginDebug.message("LoginViewBean.forwardTo():Forward URL before appending cookie is " + redirect_url);
loginDebug.message("LoginViewBean.forwardTo():Final Forward URL is " + redirect_url);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(redirect_url);
request.setAttribute(Constants.FORWARD_PARAM, Constants.FORWARD_YES_VALUE);
dispatcher.forward(request, response);
} else {
response.sendRedirect(redirect_url);
}
return;
} catch (Exception er) {
if (loginDebug.messageEnabled()) {
loginDebug.message("Session getState exception: ", er);
}
setErrorMessage(er);
}
}
ac = AuthUtils.getAuthContext(request, response, sessionID, sessionUpgrade, isBackPost);
if (sessionID != null) {
intSession = AuthD.getSession(sessionID);
}
if ((intSession != null) && (intSession.isTimedOut())) {
//Session Timeout
// clear the cookie only if cookie supported
loginDebug.message("Session timeout TRUE");
if (sessionUpgrade) {
try {
redirect_url = getPrevSuccessURLAndSetCookie();
clearGlobals();
response.sendRedirect(redirect_url);
return;
} catch (Exception e) {
loginDebug.message("Error redirecting :", e);
}
} else {
// clear AM Cookie if it exists.
if (CookieUtils.getCookieValueFromReq(request, AuthUtils.getCookieName()) != null) {
clearCookie(AuthUtils.getCookieName());
}
// clear Auth Cookie if it exists.
if (CookieUtils.getCookieValueFromReq(request, AuthUtils.getAuthCookieName()) != null) {
clearCookie(AuthUtils.getAuthCookieName());
}
loginURL = intSession.getProperty(ISAuthConstants.FULL_LOGIN_URL);
errorTemplate = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_TIMEOUT, AuthUtils.ERROR_TEMPLATE);
errorCode = AMAuthErrorCode.AUTH_TIMEOUT;
ErrorMessage = AuthUtils.getErrorVal(AMAuthErrorCode.AUTH_TIMEOUT, AuthUtils.ERROR_MESSAGE);
}
}
java.util.Locale locale = com.sun.identity.shared.locale.Locale.getLocale(AuthUtils.getLocale(ac));
fallbackLocale = locale;
rb = rbCache.getResBundle(bundleName, locale);
if (loginDebug.messageEnabled()) {
loginDebug.message("ac = " + ac);
loginDebug.message("JSPLocale = " + locale);
}
if (sessionUpgrade) {
ac.getLoginState().setForceAuth(forceAuth);
}
if (!AuthUtils.getInetDomainStatus(ac)) {
//domain inactive
if ((errorTemplate == null) || (errorTemplate.length() == 0)) {
setErrorMessage(null);
}
}
// add cookie only if cookie is supported
if (!isBackPost) {
loginURL = AuthUtils.getLoginURL(ac);
}
/*if (loginDebug.messageEnabled()) {
loginDebug.message("loginURL : " + loginURL);
}*/
// Check whether need to detect the cookie support in the browser
String cookieless = (String) request.getAttribute("displayCookieError");
if (cookieless != null && cookieless.equals("true")) {
ErrorMessage = rb.getString("nocookiesupport");
errorTemplate = "Message.jsp";
}
if (AuthUtils.isNewRequest(ac)) {
loginDebug.message("New AuthContext created");
if (AuthUtils.isCookieSupported(ac)) {
if (AuthUtils.persistAMCookie(reqDataHash)) {
enableCookieTimeToLive();
}
setCookie();
setlbCookie();
}
} else {
// check if client still have the cookie we set.
if (AuthUtils.isCookieSet(ac)) {
if (AuthUtils.checkForCookies(request, ac)) {
loginDebug.message("Client support cookie");
AuthUtils.setCookieSupported(ac, true);
} else {
loginDebug.message("Client do not support cookie");
AuthUtils.setCookieSupported(ac, false);
}
}
}
} catch (Exception e) {
ISLocaleContext localeContext = new ISLocaleContext();
localeContext.setLocale(request);
fallbackLocale = localeContext.getLocale();
rb = rbCache.getResBundle(bundleName, fallbackLocale);
if (loginDebug.messageEnabled()) {
loginDebug.message("JSPLocale = " + fallbackLocale);
}
setErrorMessage(e);
jsp_page = errorTemplate;
if (requestContext == null) {
return;
}
super.forwardTo(requestContext);
return;
}
if (errorTemplate == null || errorTemplate.isEmpty()) {
processLogin();
if (requestContext == null) {
// solve the recursive case
clearGlobals();
return;
}
}
if ((redirect_url != null) && (redirect_url.length() != 0)) {
// forward check for liberty federation, if the redirect_url
// is the federation post login servlet, use forward instead
boolean doForward = AuthUtils.isForwardSuccess(ac, request);
if (AuthUtils.isGenericHTMLClient(client_type) || doForward) {
try {
if (loginDebug.messageEnabled()) {
loginDebug.message("Send Redirect to " + redirect_url);
}
// destroy session if necessary.
InternalSession oldSession = AuthUtils.getOldSession(ac);
if (ac.getStatus() == AuthContext.Status.FAILED) {
loginDebug.message("forwardTo(): Auth failed - Destroy Session!");
if (AuthUtils.isSessionUpgrade(ac)) {
clearCookieAndDestroySession(ac);
loginDebug.message("forwardTo(): Session upgrade - " + "Restoring original Session!");
if (oldSession != null) {
ac.getLoginState().setSession(oldSession);
}
} else {
clearCookieAndDestroySession(ac);
if (oldSession != null) {
loginDebug.message("Destroy existing/old valid session");
AuthD authD = AuthD.getAuth();
authD.destroySession(oldSession.getID());
}
}
loginDebug.message("Login failure, current session destroyed!");
} else if (ac.getStatus() == AuthContext.Status.SUCCESS) {
response.setHeader("X-AuthErrorCode", "0");
if (ac.getLoginState().getForceFlag()) {
if (loginDebug.messageEnabled()) {
loginDebug.message("Forced Auth Succeed." + "Restoring updated session");
}
clearCookieAndDestroySession(ac);
ac.getLoginState().setSession(oldSession);
} else {
if (AuthUtils.isCookieSupported(ac)) {
setCookie();
clearCookie(AuthUtils.getAuthCookieName());
}
if (SystemProperties.getAsBoolean(Constants.DESTROY_SESSION_AFTER_UPGRADE) && oldSession != null) {
loginDebug.message("Destroy existing/old valid session");
AuthD authD = AuthD.getAuth();
authD.destroySession(oldSession.getID());
}
}
}
Cookie appendCookie = AuthUtils.getCookieString(ac, null);
clearGlobals();
if (doForward || redirect_url.startsWith(SSO_REDIRECT) || redirect_url.startsWith(SSO_POST)) {
if (loginDebug.messageEnabled()) {
loginDebug.message("LoginViewBean.forwardRequest=true");
loginDebug.message("LoginViewBean.forwardTo():" + "Forward URL before appending cookie is " + redirect_url);
}
//but the new isn't.
if (redirect_url.indexOf("?") == -1) {
redirect_url = redirect_url + "?" + appendCookie.getName() + "=" + URLEncDec.encode(appendCookie.getValue());
} else {
redirect_url = redirect_url + "&" + appendCookie.getName() + "=" + URLEncDec.encode(appendCookie.getValue());
}
if (loginDebug.messageEnabled()) {
loginDebug.message("LoginViewBean.forwardTo():" + "Final Forward URL is " + redirect_url);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(redirect_url);
request.setAttribute(Constants.FORWARD_PARAM, Constants.FORWARD_YES_VALUE);
dispatcher.forward(request, response);
} else {
response.sendRedirect(redirect_url);
}
forward = false;
return;
} catch (IOException e) {
loginDebug.error("LoginViewBean.forwardTo(): There was an IOException doing the forward/redirect", e);
ResultVal = rb.getString("redirect.error");
} catch (Exception e) {
loginDebug.error("LoginViewBean.forwardTo(): There was an Exception doing the forward/redirect", e);
setErrorMessage(e);
redirect_url = null;
}
}
}
if (forward) {
forward = false;
super.forwardTo(requestContext);
}
clearGlobals();
}
use of com.iplanet.dpro.session.service.InternalSession in project OpenAM by OpenRock.
the class LoginViewBean method getPrevSuccessURLAndSetCookie.
/** Retrieves the original AuthContext and the session,
* sets the cookie and retrieves the original
* success login url.
* @return redirect_url, a String
*/
String getPrevSuccessURLAndSetCookie() {
loginDebug.message("Restoring original Session !");
InternalSession oldSession = AuthUtils.getOldSession(ac);
clearCookieAndDestroySession(ac);
if (oldSession != null) {
ac.getLoginState().setSession(oldSession);
}
String redirect_url = oldSession.getProperty(ISAuthConstants.SUCCESS_URL);
return redirect_url;
}
Aggregations