/** * Returns the SSOToken of the user. If user has not authenticated re-directs the user to login * page */ private SSOToken getSSOToken(HttpServletRequest request, HttpServletResponse response) throws IOException { SSOToken token = null; try { /* SSOTokenManager.createSSOToken() throws an SSOException if the * token is not valid, so for a invalid token manager.isValidToken() * will never get executed for an invalid token. */ if (((token = tokenManager.createSSOToken(request)) == null) || !tokenManager.isValidToken(token)) { if (debug.messageEnabled()) { debug.message( "CDCClientServlet.getSSOToken:SSOToken is " + "either null or not valid: " + token + "\nRedirecting for authentication"); } token = null; } } catch (com.iplanet.sso.SSOException e) { if (debug.messageEnabled()) { debug.message("CDCClientServlet.getSSOToken:SSOException " + "caught= " + e); } token = null; } return (token); }
public Subject getAuthZSubject(HttpServletRequest req) throws RestException { try { String tokenId = req.getHeader(RestServiceManager.SUBJECT_HEADER_NAME); if ((tokenId == null) || (tokenId.trim().length() == 0)) { SSOTokenManager mgr = SSOTokenManager.getInstance(); SSOToken token = mgr.createSSOToken(req); return SubjectUtils.createSubject(token); } else { int idx = tokenId.indexOf(':'); if (idx != -1) { tokenId = tokenId.substring(idx + 1); } SSOTokenManager mgr = SSOTokenManager.getInstance(); SSOToken token = mgr.createSSOToken(tokenId); return SubjectUtils.createSubject(token); } } catch (SSOException ex) { throw new RestException(1, ex); } }
private String getAuthModulesFromSSOToken(OAuth2Request request) { String authModules = null; try { SSOToken token = ssoTokenManager.createSSOToken(ServletUtils.getRequest(request.<Request>getRequest())); if (token != null) { authModules = token.getProperty(ISAuthConstants.AUTH_TYPE); } } catch (SSOException e) { logger.warning("Could not get list of auth modules from authentication", e); } return authModules; }
/** * Returns names of all realms included in the subtree rooted by the realm indicated in the query * url. * * <p>Names are unsorted and given as full paths. * * <p>Filtering, sorting, and paging of results is not supported. * * <p>{@inheritDoc} */ @Override public void queryCollection( final ServerContext context, final QueryRequest request, final QueryResultHandler handler) { final String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context); final RealmContext realmContext = context.asContext(RealmContext.class); final String realmPath = realmContext.getResolvedRealm(); try { final SSOTokenManager mgr = SSOTokenManager.getInstance(); final SSOToken ssoToken = mgr.createSSOToken(getCookieFromServerContext(context)); final OrganizationConfigManager ocm = new OrganizationConfigManager(ssoToken, realmPath); final List<String> realmsInSubTree = new ArrayList<String>(); realmsInSubTree.add(realmPath); for (final Object subRealmRelativePath : ocm.getSubOrganizationNames("*", true)) { if (realmPath.endsWith("/")) { realmsInSubTree.add(realmPath + subRealmRelativePath); } else { realmsInSubTree.add(realmPath + "/" + subRealmRelativePath); } } debug.message("RealmResource :: QUERY : performed by " + principalName); for (final Object realmName : realmsInSubTree) { JsonValue val = new JsonValue(realmName); Resource resource = new Resource((String) realmName, "0", val); handler.handleResource(resource); } handler.handleResult(new QueryResult()); } catch (SSOException ex) { debug.error("RealmResource :: QUERY by " + principalName + " failed : " + ex); handler.handleError(ResourceException.getException(ResourceException.FORBIDDEN)); } 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 handler.handleError(ResourceException.getException(ResourceException.FORBIDDEN)); break; default: handler.handleError(ResourceException.getException(ResourceException.INTERNAL_ERROR)); break; } } }
private SSOToken validateAssertionSubjectSession( TokenGenerationServiceInvocationState invocationState) throws ForbiddenException { SSOToken subjectToken; SSOTokenManager tokenManager; try { tokenManager = SSOTokenManager.getInstance(); subjectToken = tokenManager.createSSOToken(invocationState.getSsoTokenString()); } catch (SSOException e) { logger.debug( "Exception caught creating the SSO token from the token string, almost certainly " + "because token string does not correspond to a valid session: " + e); throw new ForbiddenException(e.toString(), e); } if (!tokenManager.isValidToken(subjectToken)) { throw new ForbiddenException("SSO token string does not correspond to a valid SSOToken"); } try { AMIdentity subjectIdentity = IdUtils.getIdentity(subjectToken); String invocationRealm = invocationState.getRealm(); String subjectSessionRealm = DNMapper.orgNameToRealmName(subjectIdentity.getRealm()); logger.debug( "TokenGenerationService:validateAssertionSubjectSession subjectRealm " + subjectSessionRealm + " invocation realm: " + invocationRealm); if (!invocationRealm.equalsIgnoreCase(subjectSessionRealm)) { logger.error( "TokenGenerationService:validateAssertionSubjectSession realms do not match: Subject realm : " + subjectSessionRealm + " invocation realm: " + invocationRealm); throw new ForbiddenException("SSO token subject realm does not match invocation realm"); } } catch (SSOException | IdRepoException e) { logger.error( "TokenGenerationService:validateAssertionSubjectSession error while validating identity : " + e); throw new ForbiddenException(e.toString(), e); } return subjectToken; }
private void initAuthSessions() throws SSOException, SessionException { if (authSession == null) { authSession = getSS().getAuthenticationSession(defaultOrg, null); if (authSession == null) { debug.error("AuthD failed to get auth session"); throw new SessionException(BUNDLE_NAME, "gettingSessionFailed", null); } String clientID = authSession.getClientID(); authSession.setProperty("Principal", clientID); authSession.setProperty("Organization", defaultOrg); authSession.setProperty("Host", authSession.getID().getSessionServer()); DN dn = new DN(clientID); if (dn.isDN()) { String[] tokens = dn.explodeDN(true); String id = "id=" + tokens[0] + ",ou=user," + ServiceManager.getBaseDN(); authSession.setProperty(Constants.UNIVERSAL_IDENTIFIER, id); } SSOTokenManager ssoManager = SSOTokenManager.getInstance(); ssoAuthSession = ssoManager.createSSOToken(authSession.getID().toString()); } }
private int validateTokenId(HttpServletRequest request) throws ServletException, IOException { String tokenId = request.getHeader(RestServiceManager.SUBJECT_HEADER_NAME); String hashed = request.getParameter(RestServiceManager.HASHED_SUBJECT_QUERY); if (((tokenId == null) || (tokenId.trim().length() == 0)) && ((hashed == null) || (hashed.trim().length() == 0))) { // by pass the check return HttpServletResponse.SC_OK; } if ((tokenId == null) || (tokenId.trim().length() == 0)) { try { SSOTokenManager mgr = SSOTokenManager.getInstance(); SSOToken token = mgr.createSSOToken(request); tokenId = token.getTokenID().toString(); } catch (SSOException e) { return HttpServletResponse.SC_UNAUTHORIZED; } } if (!Boolean.parseBoolean( SystemProperties.get(RestServiceManager.DISABLE_HASHED_SUBJECT_CHECK, "false"))) { if ((hashed == null) || (hashed.trim().length() == 0)) { return HttpServletResponse.SC_UNAUTHORIZED; } else { int idx = tokenId.indexOf(':'); if (idx != -1) { tokenId = tokenId.substring(idx + 1); } if (!Hash.hash(tokenId).equals(hashed)) { return HttpServletResponse.SC_UNAUTHORIZED; } } } return HttpServletResponse.SC_OK; }
/* * Process the XMLRequest */ private AuthXMLResponse processAuthXMLRequest( String xml, AuthXMLRequest authXMLRequest, HttpServletRequest servletRequest, HttpServletResponse servletResponse) { if (messageEnabled) { debug.message("authXMLRequest is : " + authXMLRequest); } int requestType = authXMLRequest.getRequestType(); String sessionID = authXMLRequest.getAuthIdentifier(); String orgName = authXMLRequest.getOrgName(); AuthContextLocal authContext = authXMLRequest.getAuthContext(); LoginState loginState = AuthUtils.getLoginState(authContext); String params = authXMLRequest.getParams(); List envList = authXMLRequest.getEnvironment(); Map envMap = toEnvMap(envList); AuthXMLResponse authResponse = new AuthXMLResponse(requestType); authResponse.setAuthContext(authContext); authResponse.setAuthIdentifier(sessionID); if (messageEnabled) { debug.message("authContext is : " + authContext); debug.message("requestType : " + requestType); } if (authXMLRequest.getValidSessionNoUpgrade()) { authResponse.setAuthXMLRequest(authXMLRequest); authResponse.setValidSessionNoUpgrade(true); return authResponse; } String securityEnabled = null; try { securityEnabled = AuthUtils.getRemoteSecurityEnabled(); } catch (AuthException auExp) { debug.error("Got Exception", auExp); setErrorCode(authResponse, auExp); return authResponse; } if (debug.messageEnabled()) { debug.message("Security Enabled = " + securityEnabled); } if (requestType != 0) { if ((securityEnabled != null) && (securityEnabled.equals("true"))) { security = true; String indexNameLoc = authXMLRequest.getIndexName(); AuthContext.IndexType indexTypeLoc = authXMLRequest.getIndexType(); if (indexTypeLoc == null) { indexTypeLoc = AuthUtils.getIndexType(authContext); indexNameLoc = AuthUtils.getIndexName(authContext); } if (debug.messageEnabled()) { debug.message("Index Name Local : " + indexNameLoc); debug.message("Index Type Local : " + indexTypeLoc); } if (((indexTypeLoc == null) || (indexNameLoc == null)) || !((indexTypeLoc == AuthContext.IndexType.MODULE_INSTANCE) && indexNameLoc.equals("Application"))) { try { String ssoTokenID = authXMLRequest.getAppSSOTokenID(); if (debug.messageEnabled()) { debug.message("Session ID = : " + ssoTokenID); } SSOTokenManager manager = SSOTokenManager.getInstance(); SSOToken appSSOToken = manager.createSSOToken(ssoTokenID); // if the token isn't valid, let the client know so they // retry if (!manager.isValidToken(appSSOToken)) { if (debug.messageEnabled()) { debug.message("App SSOToken is not valid"); } setErrorCode( authResponse, new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null)); return authResponse; } else { debug.message("App SSOToken is VALID"); } } catch (SSOException ssoe) { // token is unknown to OpenAM, let the client know so they // can retry if (debug.messageEnabled()) { debug.message("App SSOToken is not valid: " + ssoe.getMessage()); } setErrorCode( authResponse, new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null)); return authResponse; } catch (Exception exp) { debug.error("Got Exception", exp); setErrorCode(authResponse, exp); return authResponse; } } } } else { security = false; } // if index type is level and choice callback has a // selected choice then start module based authentication. if ((AuthUtils.getIndexType(authContext) == AuthContext.IndexType.LEVEL) || (AuthUtils.getIndexType(authContext) == AuthContext.IndexType.COMPOSITE_ADVICE)) { Callback[] callbacks = authXMLRequest.getSubmittedCallbacks(); if (messageEnabled) { debug.message("Callbacks are : " + callbacks); } if (callbacks != null) { if (messageEnabled) { debug.message("Callback length is : " + callbacks.length); } if (callbacks[0] instanceof ChoiceCallback) { ChoiceCallback cc = (ChoiceCallback) callbacks[0]; int[] selectedIndexes = cc.getSelectedIndexes(); int selected = selectedIndexes[0]; String[] choices = cc.getChoices(); String indexName = choices[selected]; if (messageEnabled) { debug.message("Selected Index is : " + indexName); } authXMLRequest.setIndexType("moduleInstance"); authXMLRequest.setIndexName(indexName); authXMLRequest.setRequestType(AuthXMLRequest.LoginIndex); requestType = AuthXMLRequest.LoginIndex; } } } AuthContext.Status loginStatus = AuthContext.Status.IN_PROGRESS; HttpServletRequest clientRequest = authXMLRequest.getClientRequest(); if (loginState != null) { loginState.setHttpServletRequest(clientRequest); loginState.setHttpServletResponse(authXMLRequest.getClientResponse()); if (clientRequest != null) { loginState.setParamHash(AuthUtils.parseRequestParameters(clientRequest)); } } switch (requestType) { case AuthXMLRequest.NewAuthContext: try { processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext); postProcess(loginState, authResponse); } catch (Exception ex) { debug.error("Error in NewAuthContext ", ex); setErrorCode(authResponse, ex); } break; case AuthXMLRequest.Login: try { if (sessionID != null && sessionID.equals("0")) { processNewRequest( servletRequest, servletResponse, authResponse, loginState, authContext); } String clientHost = null; if (security) { clientHost = authXMLRequest.getHostName(); if (messageEnabled) { debug.message("Client Host from Request = " + clientHost); } } if ((clientHost == null) && (servletRequest != null)) { clientHost = ClientUtils.getClientIPAddress(servletRequest); } loginState.setClient(clientHost); authContext.login(); // setServletRequest(servletRequest,authContext); processRequirements(xml, authContext, authResponse, params, servletRequest); loginStatus = authContext.getStatus(); authResponse.setRemoteRequest(loginState.getHttpServletRequest()); authResponse.setRemoteResponse(loginState.getHttpServletResponse()); postProcess(loginState, authResponse); checkACException(authResponse, authContext); } catch (Exception ex) { debug.error("Error during login ", ex); setErrorCode(authResponse, ex); authResponse.setLoginStatus(authContext.getStatus()); } break; case AuthXMLRequest.LoginIndex: try { AuthContext.IndexType indexType = authXMLRequest.getIndexType(); String indexName = authXMLRequest.getIndexName(); if (messageEnabled) { debug.message("indexName is : " + indexName); debug.message("indexType is : " + indexType); } if (sessionID != null && sessionID.equals("0")) { processNewRequest( servletRequest, servletResponse, authResponse, loginState, authContext); } String clientHost = null; if (security) { clientHost = authXMLRequest.getHostName(); if (messageEnabled) { debug.message("Client Host from Request = " + clientHost); } } if ((clientHost == null) && (servletRequest != null)) { clientHost = ClientUtils.getClientIPAddress(servletRequest); } loginState.setClient(clientHost); String locale = authXMLRequest.getLocale(); if (locale != null && locale.length() > 0) { if (debug.messageEnabled()) { debug.message("locale is : " + locale); } authContext.login(indexType, indexName, envMap, locale); } else { authContext.login(indexType, indexName, envMap, null); } // setServletRequest(servletRequest,authContext); processRequirements(xml, authContext, authResponse, params, servletRequest); loginStatus = authContext.getStatus(); authResponse.setRemoteRequest(loginState.getHttpServletRequest()); authResponse.setRemoteResponse(loginState.getHttpServletResponse()); postProcess(loginState, authResponse); checkACException(authResponse, authContext); } catch (Exception ex) { debug.error("Exception during LoginIndex", ex); setErrorCode(authResponse, ex); } break; case AuthXMLRequest.LoginSubject: try { Subject subject = authXMLRequest.getSubject(); authContext.login(subject); // setServletRequest(servletRequest,authContext); processRequirements(xml, authContext, authResponse, params, servletRequest); postProcess(loginState, authResponse); loginStatus = authContext.getStatus(); checkACException(authResponse, authContext); } catch (AuthLoginException ale) { debug.error("Exception during LoginSubject", ale); setErrorCode(authResponse, ale); } break; case AuthXMLRequest.SubmitRequirements: try { // setServletRequest(servletRequest,authContext); Callback[] submittedCallbacks = authXMLRequest.getSubmittedCallbacks(); authContext.submitRequirements(submittedCallbacks); Callback[] reqdCallbacks = null; if (authContext.hasMoreRequirements()) { reqdCallbacks = authContext.getRequirements(); authResponse.setReqdCallbacks(reqdCallbacks); } authResponse.setRemoteRequest(loginState.getHttpServletRequest()); authResponse.setRemoteResponse(loginState.getHttpServletResponse()); postProcess(loginState, authResponse); loginStatus = authContext.getStatus(); authResponse.setLoginStatus(loginStatus); InternalSession oldSession = loginState.getOldSession(); authResponse.setOldSession(oldSession); checkACException(authResponse, authContext); } catch (Exception ex) { debug.error("Error during submit requirements ", ex); setErrorCode(authResponse, ex); } break; case AuthXMLRequest.QueryInformation: try { if (sessionID != null && sessionID.equals("0")) { processNewRequest( servletRequest, servletResponse, authResponse, loginState, authContext); } Set moduleNames = authContext.getModuleInstanceNames(); authResponse.setModuleNames(moduleNames); authResponse.setAuthContext(authContext); postProcess(loginState, authResponse); checkACException(authResponse, authContext); } catch (Exception ex) { debug.error("Error during Query Information", ex); setErrorCode(authResponse, ex); } break; case AuthXMLRequest.Logout: // Object loginContext = null; // InternalSession intSess = null; // SSOToken token = null; // boolean logoutCalled = false; if (sessionID != null && !sessionID.equals("0")) { /*intSess = AuthD.getSession(sessionID); try { token = SSOTokenManager.getInstance(). createSSOToken(sessionID); if (debug.messageEnabled()) { debug.message("AuthXMLHandler." + "processAuthXMLRequest: Created token " + "during logout = "+token); } } catch (com.iplanet.sso.SSOException ssoExp) { if (debug.messageEnabled()) { debug.message("AuthXMLHandler.processAuthXMLRequest:" + "SSOException checking validity of SSO Token"); } }*/ try { AuthUtils.logout(sessionID, servletRequest, servletResponse); } catch (com.iplanet.sso.SSOException ssoExp) { if (debug.messageEnabled()) { debug.message( "AuthXMLHandler.processAuthXMLRequest:" + "SSOException checking validity of SSO Token"); } } } /*if (intSess != null) { loginContext = intSess.getObject(ISAuthConstants. LOGIN_CONTEXT); } try { if (loginContext != null) { if (loginContext instanceof javax.security.auth.login.LoginContext) { javax.security.auth.login.LoginContext lc = (javax.security.auth.login.LoginContext) loginContext; lc.logout(); } else { com.sun.identity.authentication.jaas.LoginContext jlc = (com.sun.identity.authentication.jaas. LoginContext) loginContext; jlc.logout(); } logoutCalled = true; } } catch (javax.security.auth.login.LoginException loginExp) { debug.error("AuthXMLHandler.processAuthXMLRequest: " + "Cannot Execute module Logout", loginExp); } Set postAuthSet = null; if (intSess != null) { postAuthSet = (Set) intSess.getObject(ISAuthConstants. POSTPROCESS_INSTANCE_SET); } if ((postAuthSet != null) && !(postAuthSet.isEmpty())) { AMPostAuthProcessInterface postLoginInstance=null; for(Iterator iter = postAuthSet.iterator(); iter.hasNext();) { try { postLoginInstance = (AMPostAuthProcessInterface) iter.next(); postLoginInstance.onLogout(servletRequest, servletResponse, token); } catch (Exception exp) { debug.error("AuthXMLHandler.processAuthXMLRequest: " + "Failed in post logout.", exp); } } } else { String plis = null; if (intSess != null) { plis = intSess.getProperty( ISAuthConstants.POST_AUTH_PROCESS_INSTANCE); } if (plis != null && plis.length() > 0) { StringTokenizer st = new StringTokenizer(plis, "|"); if (token != null) { while (st.hasMoreTokens()) { String pli = (String)st.nextToken(); try { AMPostAuthProcessInterface postProcess = (AMPostAuthProcessInterface) Thread.currentThread(). getContextClassLoader(). loadClass(pli).newInstance(); postProcess.onLogout(servletRequest, servletResponse, token); } catch (Exception e) { debug.error("AuthXMLHandler." + "processAuthXMLRequest:" + pli, e); } } } } } try { boolean isTokenValid = SSOTokenManager.getInstance(). isValidToken(token); if ((token != null) && isTokenValid) { AuthD.getAuth().logLogout(token); Session session = Session.getSession( new SessionID(sessionID)); session.logout(); debug.message("logout successful."); } } catch (com.iplanet.dpro.session.SessionException sessExp) { if (debug.messageEnabled()) { debug.message("AuthXMLHandler." + "processAuthXMLRequest: SessionException" + " checking validity of SSO Token"); } } catch (com.iplanet.sso.SSOException ssoExp) { if (debug.messageEnabled()) { debug.message("AuthXMLHandler." + "processAuthXMLRequest: SSOException " + "checking validity of SSO Token"); } }*/ authResponse.setLoginStatus(AuthContext.Status.COMPLETED); break; case AuthXMLRequest.Abort: try { authContext.abort(); loginStatus = authContext.getStatus(); authResponse.setLoginStatus(loginStatus); checkACException(authResponse, authContext); } catch (AuthLoginException ale) { debug.error("Error aborting ", ale); setErrorCode(authResponse, ale); } break; } if (messageEnabled) { debug.message("loginStatus: " + loginStatus); if (authContext != null) { debug.message("error Code: " + authContext.getErrorCode()); debug.message("error Template: " + authContext.getErrorTemplate()); } } if (loginStatus == AuthContext.Status.FAILED) { if ((authContext.getErrorMessage() != null) && (authContext .getErrorMessage() .equals( AMResourceBundleCache.getInstance() .getResBundle( "amAuthLDAP", com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale())) .getString(ISAuthConstants.EXCEED_RETRY_LIMIT)))) { loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED); } if ((authContext.getErrorCode() != null) && ((authContext.getErrorCode()).length() > 0)) { authResponse.setErrorCode(authContext.getErrorCode()); } checkACException(authResponse, authContext); if ((authContext.getErrorTemplate() != null) && ((authContext.getErrorTemplate()).length() > 0)) { authResponse.setErrorTemplate(authContext.getErrorTemplate()); } // Account Lockout Warning Check if ((authContext.getErrorCode() != null) && (authContext.getErrorCode().equals(AMAuthErrorCode.AUTH_INVALID_PASSWORD))) { String lockWarning = authContext.getLockoutMsg(); if ((lockWarning != null) && (lockWarning.length() > 0)) { authResponse.setErrorMessage(lockWarning); } } } return authResponse; }