use of com.iplanet.dpro.session.SessionID 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.SessionID in project OpenAM by OpenRock.
the class SmsRealmProvider method handleQuery.
@Override
public Promise<QueryResponse, ResourceException> handleQuery(Context context, QueryRequest request, QueryResourceHandler handler) {
if (!"true".equals(request.getQueryFilter().toString())) {
return new NotSupportedException("Query not supported: " + request.getQueryFilter()).asPromise();
}
if (request.getPagedResultsCookie() != null || request.getPagedResultsOffset() > 0 || request.getPageSize() > 0) {
return new NotSupportedException("Query paging not currently supported").asPromise();
}
final String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
try {
final SessionID sessionID = new SessionID(getUserSsoToken(context).getTokenID().toString());
final String realmPath = coreWrapper.convertOrgNameToRealmName(sessionCache.getSession(sessionID).getClientDomain());
final OrganizationConfigManager ocm = new OrganizationConfigManager(getUserSsoToken(context), realmPath);
//Return realm query is being performed on
handler.handleResource(getResource(getJsonValue(realmPath)));
for (final Object subRealmRelativePath : ocm.getSubOrganizationNames("*", true)) {
String realmName;
if (realmPath.endsWith("/")) {
realmName = realmPath + subRealmRelativePath;
} else {
realmName = realmPath + "/" + subRealmRelativePath;
}
handler.handleResource(getResource(getJsonValue(realmName)));
}
debug.message("RealmResource :: QUERY : performed by {}", principalName);
return newResultPromise(newQueryResponse());
} catch (SSOException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex);
return new ForbiddenException().asPromise();
} catch (SessionException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex);
return new InternalServerErrorException().asPromise();
} catch (SMSException ex) {
debug.error("RealmResource :: QUERY by " + principalName + " failed :" + ex);
switch(ex.getExceptionCode()) {
case STATUS_NO_PERMISSION:
// This exception will be thrown if permission to read realms from SMS has not been delegated
return new ForbiddenException().asPromise();
default:
return new InternalServerErrorException().asPromise();
}
}
}
use of com.iplanet.dpro.session.SessionID in project OpenAM by OpenRock.
the class AuthIdHelperTest method shouldThrowExceptionWhenGeneratingAuthIdAndKeyAliasIsNull.
@Test
public void shouldThrowExceptionWhenGeneratingAuthIdAndKeyAliasIsNull() throws SSOException, SMSException, SignatureException {
//Given
LoginConfiguration loginConfiguration = mock(LoginConfiguration.class);
AuthContextLocalWrapper authContext = mock(AuthContextLocalWrapper.class);
given(authContext.getOrgDN()).willReturn("ORG_DN");
given(authContext.getSessionID()).willReturn(new SessionID("SESSION_ID"));
given(loginConfiguration.getIndexType()).willReturn(AuthIndexType.NONE);
given(loginConfiguration.getIndexValue()).willReturn(null);
mockGetSigningKey("ORG_DN", true);
//When
boolean exceptionCaught = false;
try {
authIdHelper.createAuthId(loginConfiguration, authContext);
fail();
} catch (RestAuthException e) {
exceptionCaught = true;
}
//Then
assertTrue(exceptionCaught);
}
use of com.iplanet.dpro.session.SessionID in project OpenAM by OpenRock.
the class LoginServlet method initializeRequestContext.
/**
*
*
*/
protected void initializeRequestContext(RequestContext requestContext) {
super.initializeRequestContext(requestContext);
// Set a view bean manager in the request context. This must be
// done at the module level because the view bean manager is
// module specifc.
ViewBeanManager viewBeanManager = new ViewBeanManager(requestContext, PACKAGE_NAME);
((RequestContextImpl) requestContext).setViewBeanManager(viewBeanManager);
HttpServletRequest request = requestContext.getRequest();
HttpServletResponse response = requestContext.getResponse();
// by redirecting the response with dummy cookie.
if (checkForCookiesInBrowser(request, response, debug)) {
throw new CompleteRequestException();
}
// Check content length
try {
RequestUtils.checkContentLength(request);
} catch (L10NMessageImpl e) {
if (debug.messageEnabled()) {
ISLocaleContext localeContext = new ISLocaleContext();
localeContext.setLocale(request);
java.util.Locale locale = localeContext.getLocale();
debug.message("LoginServlet: " + e.getL10NMessage(locale));
}
AuthExceptionViewBean vb = (AuthExceptionViewBean) viewBeanManager.getViewBean(com.sun.identity.authentication.UI.AuthExceptionViewBean.class);
vb.forwardTo(requestContext);
throw new CompleteRequestException();
}
// Check if the hostname in the URL is an FQDN else
// redirect to the fqdn
String client_type = AuthUtils.getClientType(request);
if (debug.messageEnabled()) {
debug.message("Client Type = " + client_type);
}
String hostName = AuthUtils.getHostName(request);
if (!AuthUtils.isValidFQDNRequest(hostName)) {
try {
String newHN = AuthUtils.getValidFQDNResource(hostName, request);
if (debug.messageEnabled()) {
debug.message("FQDN = " + newHN);
}
if (AuthUtils.isGenericHTMLClient(client_type)) {
debug.message("This is HTML");
response.sendRedirect(newHN);
} else {
String fileName = AuthUtils.getDefaultFileName(request, REDIRECT_JSP);
if (debug.messageEnabled()) {
debug.message("Forward to : " + fileName);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(fileName);
dispatcher.forward(request, response);
}
} catch (Exception e) {
// came here continue
}
throw new CompleteRequestException();
}
final boolean isLoginRequest = LOGIN_PAGE_NAME.equals(getPageName(request));
String cookieURL = AuthUtils.getCookieURLForSessionUpgrade(request);
if (cookieURL != null && isLoginRequest) {
rerouteRequest(request, response, cookieURL);
return;
}
// Check whether this is the correct server to accept the client
// response.
String authCookieValue = AuthUtils.getAuthCookieValue(request);
if ((authCookieValue != null) && (authCookieValue.length() != 0) && (!authCookieValue.equalsIgnoreCase("LOGOUT"))) {
//send Auth request to cookie (original) server
try {
SessionID sessionID = new SessionID(authCookieValue);
cookieURL = AuthUtils.getCookieURL(sessionID);
} catch (Exception e) {
if (debug.messageEnabled()) {
debug.message("LoginServlet error in Session : " + e.toString());
}
}
if (debug.messageEnabled()) {
debug.message("cookieURL : " + cookieURL);
}
if (isLoginRequest && cookieURL != null && !cookieURL.isEmpty() && !AuthUtils.isLocalServer(cookieURL, true) && !AuthUtils.isSessionUpgradeOrForceAuth(request)) {
rerouteRequest(request, response, cookieURL);
}
}
}
use of com.iplanet.dpro.session.SessionID 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();
}
Aggregations