List of usage examples for javax.servlet.http HttpServletRequest isSecure
public boolean isSecure();
From source file:org.josso.wls81.agent.WLSAgentServletFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]"); try {/*w w w .j a va2 s . co m*/ // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(request.getServerName(), contextPath)) { filterChain.doFilter(hreq, hres); log.warn("JOSSO WLS 8.1 Filter is running on a non-JOSSO Partner application!"); return; } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(request.getServerName(), contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { if (log.isDebugEnabled()) log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) { if (log.isDebugEnabled()) log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // logout user (remove data from the session and webserver) // (The LoginModule.logout method is never called // for the WebLogic Authentication providers or custom Authentication providers. // This is simply because once the principals are created and placed into a subject, // the WebLogic Security Framework no longer controls the lifecycle of the subject) _agent.prepareNonCacheResponse(hres); ServletAuthentication.logout(hreq); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); if (log.isDebugEnabled()) log.debug("Session is: " + session); LocalSession localSession = new GenericServletLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie and a security check without assertion was received ... // This means that the user could not be identified during a login optional process ... // go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { // If saved request is NOT null, we're in the middle of another process ... if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can go back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } // This URI should be protected by SSO, go on ... // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); SSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException( "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r; log.debug("Creating Security Context for Session [" + session + "]"); r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // TODO : Not supported ... session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can go back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]"); } }
From source file:org.josso.servlet.agent.GenericServletSSOAgentFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath()); try {// w ww .j av a 2 s.c o m // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(vhost, contextPath)) { filterChain.doFilter(hreq, hres); if (log.isDebugEnabled()) log.debug("Context is not a josso partner app : " + hreq.getContextPath()); return; } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { if (log.isDebugEnabled()) log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) { if (log.isDebugEnabled()) log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } // Get our session ... String jossoSessionId = (cookie == null) ? null : cookie.getValue(); GenericServletLocalSession localSession = new GenericServletLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) { log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest( cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } if (log.isDebugEnabled()) log.debug("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); GenericServletSSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException("No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not supported : session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:com.adito.applications.actions.GetHTMLApplicationAction.java
public ActionForward onExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String launchSessionId = request.getParameter(LaunchSession.LAUNCH_ID); LaunchSession launchSession = LaunchSessionFactory.getInstance().getLaunchSession(launchSessionId); if (launchSession == null) { throw new Exception("No launch session id " + launchSessionId); }/*from w w w . jav a 2 s. c om*/ final ApplicationShortcut shortcut = (ApplicationShortcut) launchSession.getResource(); launchSession.checkAccessRights(null, getSessionInfo(request)); ExtensionDescriptor app = ExtensionStore.getInstance().getExtensionDescriptor(shortcut.getApplication()); if (app == null) { throw new Exception("No application named " + shortcut.getApplication() + "."); } if (!(app.getExtensionType() instanceof HtmlType)) { throw new Exception( getClass().getName() + " only supports applications of type " + HtmlType.class + "."); } // Get the primary VPN client ticket HtmlType type = (HtmlType) app.getExtensionType(); File file = new File(app.getApplicationBundle().getBaseDir(), type.getTemplate()); if (log.isDebugEnabled()) log.debug("Loading template " + file.getAbsolutePath()); InputStream in = null; StringBuffer template = new StringBuffer((int) file.length()); try { in = new FileInputStream(file); String line = null; BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while ((line = reader.readLine()) != null) { if (template.length() != 0) { template.append("\n"); } template.append(line); } } finally { Util.closeStream(in); } if (log.isDebugEnabled()) log.debug("Parsing parameters."); for (Iterator i = shortcut.getParameters().entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String content = (String) entry.getValue(); VariableReplacement r = new VariableReplacement(); r.setApplicationShortcut(app, null); r.setServletRequest(request); r.setLaunchSession(launchSession); entry.setValue(r.replace(content)); } if (log.isDebugEnabled()) log.debug("Template loaded, doing standard replacements."); VariableReplacement r = new VariableReplacement(); r.setApplicationShortcut(app, shortcut.getParameters()); r.setServletRequest(request); r.setLaunchSession(launchSession); String templateText = r.replace(template.toString()); ReplacementEngine engine = new ReplacementEngine(); String tunnels = request.getParameter("tunnels"); if (tunnels != null && !tunnels.equals("")) { StringTokenizer t = new StringTokenizer(tunnels, ","); while (t.hasMoreTokens()) { String name = null; String hostname = null; int port = -1; try { String tunnel = t.nextToken(); StringTokenizer t2 = new StringTokenizer(tunnel, ":"); name = t2.nextToken(); hostname = t2.nextToken(); port = Integer.parseInt(t2.nextToken()); } catch (Exception e) { throw new Exception("Failed to parse tunnels parameter '" + tunnels + "'.", e); } final ExtensionDescriptor.TunnelDescriptor tunnelDescriptor = app.getTunnel(name); if (tunnelDescriptor == null) { throw new Exception("No tunnel named " + name); } final String fHostname = hostname; final int fPort = port; String pattern = "\\$\\{tunnel:" + name + "\\.[^\\}]*\\}"; engine.addPattern(pattern, new Replacer() { public String getReplacement(Pattern pattern, Matcher matcher, String sequence) { String match = matcher.group(); if (match.equals("${tunnel:" + tunnelDescriptor.getName() + ".hostname}")) { return fHostname; } else if (match.equals("${tunnel:" + tunnelDescriptor.getName() + ".port}")) { return String.valueOf(fPort); } else { return ""; } } }, null); } } // Get the location of Adito as the client sees it String url = request.getParameter("adito"); if (url != null) { String host = request.getHeader(HttpConstants.HDR_HOST); if (host != null) { url = (request.isSecure() ? "https" : "http") + "://" + host; } else { throw new Exception("No adito parameter supplied."); } } final URL aditoUrl = new URL(url); engine.addPattern("\\$\\{adito:[^\\}]*\\}", new Replacer() { public String getReplacement(Pattern pattern, Matcher matcher, String sequence) { String match = matcher.group(); try { String param = match.substring(14, match.length() - 1); if (param.equals("host")) { return aditoUrl.getHost(); } else if (param.equals("port")) { return String.valueOf( aditoUrl.getPort() == -1 ? (aditoUrl.getProtocol().equals("https") ? 443 : 80) : aditoUrl.getPort()); } else if (param.equals("protocol")) { return aditoUrl.getProtocol(); } else { throw new Exception("Unknow variable."); } } catch (Throwable t) { log.error("Failed to replace " + match + ".", t); } return ""; } }, null); String processed = engine.replace(templateText); if (log.isDebugEnabled()) log.debug("Returning " + processed); Util.noCache(response); response.setContentType("text/html"); response.setContentLength(processed.length()); request.setAttribute(Constants.REQ_ATTR_COMPRESS, Boolean.FALSE); OutputStream out = response.getOutputStream(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out)); pw.print(processed); pw.flush(); Policy pol = PolicyDatabaseFactory.getInstance() .getGrantingPolicyForUser(launchSession.getSession().getUser(), shortcut); CoreServlet.getServlet() .fireCoreEvent(new ResourceAccessEvent(this, ApplicationShortcutEventConstants.APPLICATION_SHORTCUT_LAUNCHED, shortcut, pol, launchSession.getSession(), CoreEvent.STATE_SUCCESSFUL) .addAttribute(CoreAttributeConstants.EVENT_ATTR_APPLICATION_NAME, app.getName()) .addAttribute(CoreAttributeConstants.EVENT_ATTR_APPLICATION_ID, shortcut.getApplication())); ////////////////////////////////////////////// return null; }
From source file:org.josso.wls10.agent.WLSAgentServletFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath()); try {//from w w w . j a v a 2 s .c o m // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(request.getServerName(), contextPath)) { filterChain.doFilter(hreq, hres); log.warn("JOSSO WLS 10 Filter is running on a non-JOSSO Partner application!"); return; } String nodeId = hreq.getParameter("josso_node"); if (nodeId != null) { if (log.isDebugEnabled()) log.debug("Storing JOSSO Node id : " + nodeId); _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId); } else { nodeId = _agent.getAttribute(hreq, "JOSSO_NODE"); if (log.isDebugEnabled()) log.debug("Found JOSSO Node id : " + nodeId); } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(request.getServerName(), contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { if (log.isDebugEnabled()) log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) { if (log.isDebugEnabled()) log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // logout user (remove data from the session and webserver) // (The LoginModule.logout method is never called // for the WebLogic Authentication providers or custom Authentication providers. // This is simply because once the principals are created and placed into a subject, // the WebLogic Security Framework no longer controls the lifecycle of the subject) _agent.prepareNonCacheResponse(hres); ServletAuthentication.logout(hreq); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); if (log.isDebugEnabled()) log.debug("Session is: " + session); LocalSession localSession = new GenericServletLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, nodeId, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can go back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } // This URI should be protected by SSO, go on ... // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); SSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, nodeId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException( "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r; log.debug("Creating Security Context for Session [" + session + "]"); r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, nodeId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // TODO : Not supported ... session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can go back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:org.codehaus.wadi.web.impl.StandardHttpProxy.java
protected void doProxy(URI uri, WebInvocation context) throws ProxyingException { HttpServletRequest req = context.getHreq(); HttpServletResponse res = context.getHres(); String requestURI = getRequestURI(req); String qs = req.getQueryString(); if (qs != null) { requestURI = new StringBuffer(requestURI).append("?").append(qs).toString(); }//from w ww . j a v a 2s.com URL url = null; try { url = new URL("http", uri.getHost(), uri.getPort(), requestURI); if (_log.isTraceEnabled()) _log.trace("proxying to: " + url); } catch (MalformedURLException e) { if (_log.isWarnEnabled()) _log.warn("bad proxy url: " + url, e); throw new IrrecoverableException("bad proxy url", e); } long startTime = System.currentTimeMillis(); HttpURLConnection huc = null; String m = req.getMethod(); try { huc = (HttpURLConnection) url.openConnection(); // IOException huc.setRequestMethod(m); // ProtocolException } catch (ProtocolException e) { if (_log.isWarnEnabled()) _log.warn("unsupported http method: " + m, e); throw new IrrecoverableException("unsupported HTTP method: " + m, e); } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxy IO problem", e); throw new RecoverableException("could not open proxy connection", e); } huc.setAllowUserInteraction(false); huc.setInstanceFollowRedirects(false); // check connection header // TODO - this might need some more time: see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html String connectionHdr = req.getHeader("Connection"); // TODO - what if there are multiple values ? if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; // TODO ?? } // copy headers - inefficient, but we are constrained by servlet API { for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) { String hdr = (String) e.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) // what is going on here ? continue; // HTTP/1.1 proxies MUST parse the Connection header field before a message is forwarded and, for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token. Connection options are signaled by the presence of a connection-token in the Connection header field, not by any corresponding additional header field(s), since the additional header field may not be sent if there are no parameters associated with that connection option if (_WADI_IsSecure.equals(hdr)) // don't worry about case - we should be the only one messing with this header... continue; // strip this out - we may be being spoofed for (Enumeration f = req.getHeaders(hdr); f.hasMoreElements();) { String val = (String) f.nextElement(); if (val != null) { huc.addRequestProperty(hdr, val); } } } } // content ? boolean hasContent = false; { int contentLength = 0; String tmp = huc.getRequestProperty("Content-Length"); if (tmp != null) { try { contentLength = Integer.parseInt(tmp); } catch (NumberFormatException ignore) { // ignore } } if (contentLength > 0) hasContent = true; else hasContent = (huc.getRequestProperty("Content-Type") != null); } // proxy { huc.addRequestProperty("Via", "1.1 " + req.getLocalName() + ":" + req.getLocalPort() + " \"WADI\""); // TODO - should we be giving out personal details ? huc.addRequestProperty("X-Forwarded-For", req.getRemoteAddr()); // adds last link in request chain... // String tmp=uc.getRequestProperty("Max-Forwards"); // TODO - do we really need to bother with this ? } // cache-control { String cacheControl = huc.getRequestProperty("Cache-Control"); if (cacheControl != null && (cacheControl.indexOf("no-cache") >= 0 || cacheControl.indexOf("no-store") >= 0)) huc.setUseCaches(false); } // confidentiality { if (req.isSecure()) { huc.addRequestProperty(_WADI_IsSecure, req.getLocalAddr().toString()); } // at the other end, if this header is present we must : // wrap the request so that req.isSecure()=true, before processing... // mask the header - so it is never seen by the app. // the code for the other end should live in this class. // this code should also confirm that it not being spoofed by confirming that req.getRemoteAddress() is a cluster member... } // customize Connection huc.setDoInput(true); // client->server int client2ServerTotal = 0; { if (hasContent) { huc.setDoOutput(true); OutputStream toServer = null; try { InputStream fromClient = req.getInputStream(); // IOException toServer = huc.getOutputStream(); // IOException client2ServerTotal = copy(fromClient, toServer, 8192); } catch (IOException e) { new IrrecoverableException("problem proxying client request to server", e); } finally { if (toServer != null) { try { toServer.close(); // IOException } catch (IOException e) { _log.warn("problem closing server request stream", e); } } } } } // Connect try { huc.connect(); // IOException } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxy connection problem: " + url, e); throw new RecoverableException("could not connect to proxy target", e); } InputStream fromServer = null; // handler status codes etc. int code = 0; if (huc == null) { try { fromServer = huc.getInputStream(); // IOException } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxying problem", e); throw new IrrecoverableException("problem acquiring client output", e); } } else { code = 502; // String message="Bad Gateway: could not read server response code or message"; try { code = huc.getResponseCode(); // IOException // message=huc.getResponseMessage(); // IOException } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxying problem", e); throw new IrrecoverableException("problem acquiring http server response code/message", e); } finally { // res.setStatus(code, message); - deprecated res.setStatus(code); } if (code < 400) { // 1XX:continue, 2XX:successful, 3XX:multiple-choices... try { fromServer = huc.getInputStream(); // IOException } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxying problem", e); throw new IrrecoverableException("problem acquiring http client output", e); } } else { // 4XX:client, 5XX:server error... fromServer = huc.getErrorStream(); // why does this not throw IOException ? // TODO - do we need to use sendError()? } } // clear response defaults. res.setHeader("Date", null); res.setHeader("Server", null); // set response headers if (false) { int h = 0; String hdr = huc.getHeaderFieldKey(h); String val = huc.getHeaderField(h); while (hdr != null || val != null) { String lhdr = (hdr != null) ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) res.addHeader(hdr, val); // if (_log.isDebugEnabled()) _log.debug("res " + hdr + ": " + val); h++; hdr = huc.getHeaderFieldKey(h); val = huc.getHeaderField(h); } } else { // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ? // Try this inside Tomcat... String key; for (int i = 1; (key = huc.getHeaderFieldKey(i)) != null; i++) { key = key.toLowerCase(); String val = huc.getHeaderField(i); if (val != null && !_DontProxyHeaders.contains(key)) { res.addHeader(key, val); } } } // do we need another Via header in the response... // server->client int server2ClientTotal = 0; { if (fromServer != null) { try { OutputStream toClient = res.getOutputStream();// IOException server2ClientTotal += copy(fromServer, toClient, 8192);// IOException } catch (IOException e) { if (_log.isWarnEnabled()) _log.warn("proxying problem", e); throw new IrrecoverableException("problem proxying server response back to client", e); } finally { try { fromServer.close(); } catch (IOException e) { // well - we did our best... _log.warn("problem closing server response stream", e); } } } } huc.disconnect(); long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; if (_log.isDebugEnabled()) _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:" + elapsed + ", url:" + url); }
From source file:org.josso.jaspi.agent.JASPISSOAuthModule.java
@Override public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { HttpServletRequest hreq = (HttpServletRequest) messageInfo.getRequestMessage(); HttpServletResponse hres = (HttpServletResponse) messageInfo.getResponseMessage(); if (log.isDebugEnabled()) { log.debug("Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]"); }/*from w w w .j av a 2 s. c o m*/ try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) { contextPath = "/"; } if (!_agent.isPartnerApp(vhost, contextPath)) { if (log.isDebugEnabled()) { log.debug("Context is not a josso partner app : " + hreq.getContextPath()); } AuthStatus status = AuthStatus.SUCCESS; return status; } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } // Get our session ... HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { if (log.isDebugEnabled()) { log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'"); } //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) { log.debug("Redirecting to login url '" + loginUrl + "'"); } //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); // Request is authorized for this URI return AuthStatus.SEND_CONTINUE; } // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) { if (log.isDebugEnabled()) { log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'"); } String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) { log.debug("Redirecting to logout url '" + logoutUrl + "'"); } // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); // Request is authorized for this URI return AuthStatus.SEND_CONTINUE; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking for SSO cookie"); } Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); if (log.isDebugEnabled()) { log.debug("Session is: " + session); } // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap == null) { synchronized (this) { sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap == null) { sessionMap = Collections.synchronizedMap(new HashMap()); hreq.getSession().getServletContext().setAttribute(KEY_SESSION_MAP, sessionMap); } } } LocalSession localSession = (LocalSession) sessionMap.get(session.getId()); if (localSession == null) { localSession = new JASPILocalSession(session); // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not Supported : session.addSessionListener(this); sessionMap.put(session.getId(), localSession); } // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) { log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } JASPISSOAgentRequest customAuthRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); // Request is authorized return AuthStatus.SEND_CONTINUE; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = this.getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); AuthStatus status = AuthStatus.SEND_CONTINUE; return status; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { // If saved request is NOT null, we're in the middle of another process ... if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) { log.debug("SSO cookie is not present, attempting automatic login"); } // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) { log.debug("Redirecting to login url '" + loginUrl + "'"); } //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); //hreq.getRequestDispatcher(loginUrl).forward(hreq, hres); AuthStatus status = AuthStatus.SEND_CONTINUE; return status; } else { if (log.isDebugEnabled()) { log.debug("SSO cookie is not present, but login optional process is not required"); } } } if (log.isDebugEnabled()) { log.debug("SSO cookie is not present, checking for outbound relaying"); } if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); AuthStatus status = AuthStatus.SUCCESS; return status; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { // Ignored resources are authorized return AuthStatus.SUCCESS; } // This URI should be protected by SSO, go on ... if (log.isDebugEnabled()) { log.debug("Session is: " + session); } // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Executing agent..."); } // ------------------------------------------------------------------ // Check if a user has been authenticated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) { log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); } String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); JASPISSOAgentRequest relayRequest; if (log.isDebugEnabled()) { log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); } relayRequest = (JASPISSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! if (log.isDebugEnabled()) { log.debug("Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); } // Throw an exception, we will handle it below ! throw new RuntimeException( "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!"); } else { // Add the SSOUser as a Principal if (!clientSubject.getPrincipals().contains(entry.principal)) { clientSubject.getPrincipals().add(entry.principal); } SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, relayRequest.getNodeId()); List<String> rolesList = new ArrayList<String>(); for (int i = 0; i < ssoRolePrincipals.length; i++) { if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) { continue; } rolesList.add(ssoRolePrincipals[i].getName()); clientSubject.getPrincipals().add(ssoRolePrincipals[i]); log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]); } registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId, rolesList.toArray(new String[rolesList.size()])); } if (log.isDebugEnabled()) { log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); } if (log.isDebugEnabled()) { log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); } // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) { log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); } hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) { log.debug("Redirecting to original '" + requestURI + "'"); } hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } AuthStatus status = AuthStatus.SEND_SUCCESS; return status; } if (log.isDebugEnabled()) { log.debug("Creating Security Context for Session [" + session + "]"); } SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) { log.debug("Executed agent."); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Process request for '" + hreq.getRequestURI() + "'"); } if (entry != null) { if (log.isDebugEnabled()) { log.debug("Principal '" + entry.principal + "' has already been authenticated"); } // Add the SSOUser as a Principal if (!clientSubject.getPrincipals().contains(entry.principal)) { clientSubject.getPrincipals().add(entry.principal); } SSORole[] ssoRolePrincipals = _agent.getRoleSets(cfg.getId(), entry.ssoId, r.getNodeId()); List<String> rolesList = new ArrayList<String>(); for (int i = 0; i < ssoRolePrincipals.length; i++) { if (clientSubject.getPrincipals().contains(ssoRolePrincipals[i])) { continue; } rolesList.add(ssoRolePrincipals[i].getName()); clientSubject.getPrincipals().add(ssoRolePrincipals[i]); log.debug("Added SSORole Principal to the Subject : " + ssoRolePrincipals[i]); } registerWithCallbackHandler(entry.principal, entry.principal.getName(), entry.ssoId, rolesList.toArray(new String[rolesList.size()])); } else { log.debug("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) { log.debug("SSO Session is not valid, attempting automatic login"); } // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) { log.debug("Redirecting to login url '" + loginUrl + "'"); } //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); // Request is authorized for this URI return AuthStatus.SEND_CONTINUE; } else { if (log.isDebugEnabled()) { log.debug("SSO cookie is not present, but login optional process is not required"); } } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); clearSavedRequestURLs(hreq, hres); AuthStatus status = AuthStatus.SUCCESS; return status; } catch (Throwable t) { log.warn(t.getMessage(), t); throw new AuthException(t.getMessage()); //return AuthStatus.FAILURE; } finally { if (log.isDebugEnabled()) { log.debug("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "]"); } } }
From source file:org.josso.liferay5.agent.LiferaySSOAgentFilter.java
@Override protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; // URI pattern matching is implemented programmatically in case this filter is bound to the root web context // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs. if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI) && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI) && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI) && !hreq.getRequestURI().contains(LIFERAY_USER_URI) && !hreq.getRequestURI().contains(LIFERAY_WEB_URI) && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) { filterChain.doFilter(hreq, hres); return;//from w ww . j a v a 2s . c om } if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath()); try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); long companyId = PortalUtil.getCompanyId(request); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(vhost, contextPath)) { filterChain.doFilter(hreq, hres); if (log.isDebugEnabled()) log.debug("Context is not a josso partner app : " + hreq.getContextPath()); return; } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } // Get our session ... HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the Liferay application required its login form [/c/portal/login] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the Liferay application required its logout form [/c/portal/logout] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); LiferayLocalSession localSession = new LiferayLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) { log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest( cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } // This URI should be protected by SSO, go on ... if (log.isDebugEnabled()) log.debug("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); LiferaySSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException("No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not supported : session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:org.exist.webstart.JnlpWriter.java
/** * Write JNLP xml file to browser./*from w ww . j av a2 s . co m*/ * * @param response Object for writing to end user. * @throws java.io.IOException */ void writeJnlpXML(JnlpJarFiles jnlpFiles, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Writing JNLP file"); // Format URL: "http://host:8080/CONTEXT/webstart/exist.jnlp" final String currentUrl = request.getRequestURL().toString(); // Find BaseUrl http://host:8080/CONTEXT final int webstartPos = currentUrl.indexOf("/webstart"); final String existBaseUrl = currentUrl.substring(0, webstartPos); // Find codeBase for jarfiles http://host:8080/CONTEXT/webstart/ final String codeBase = existBaseUrl + "/webstart/"; // Perfom sanity checks int counter = 0; for (final File jar : jnlpFiles.getAllWebstartJars()) { counter++; // debugging if (jar == null || !jar.exists()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Jar file! (" + counter + ")"); return; } } // Find URL to connect to with client final String startUrl = existBaseUrl.replaceFirst("http:", "xmldb:exist:") .replaceFirst("https:", "xmldb:exist:").replaceAll("-", "%2D") + "/xmlrpc"; // response.setDateHeader("Last-Modified", mainJar.lastModified()); response.setContentType("application/x-java-jnlp-file"); try { final XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(response.getOutputStream()); writer.writeStartDocument(); writer.writeStartElement("jnlp"); writer.writeAttribute("spec", "1.0+"); writer.writeAttribute("codebase", codeBase); writer.writeAttribute("href", "exist.jnlp"); writer.writeStartElement("information"); writer.writeStartElement("title"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("vendor"); writer.writeCharacters("exist-db.org"); writer.writeEndElement(); writer.writeStartElement("homepage"); writer.writeAttribute("href", "http://exist-db.org"); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeCharacters("Integrated command-line and gui client, " + "entirely based on the XML:DB API and provides commands " + "for most database related tasks, like creating and " + "removing collections, user management, batch-loading " + "XML data or querying."); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeAttribute("kind", "short"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeAttribute("kind", "tooltip"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_logo.jpg"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_128x128.gif"); writer.writeAttribute("width", "128"); writer.writeAttribute("height", "128"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_64x64.gif"); writer.writeAttribute("width", "64"); writer.writeAttribute("height", "64"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_32x32.gif"); writer.writeAttribute("width", "32"); writer.writeAttribute("height", "32"); writer.writeEndElement(); writer.writeEndElement(); // information writer.writeStartElement("security"); writer.writeEmptyElement("all-permissions"); writer.writeEndElement(); // ---------- writer.writeStartElement("resources"); writer.writeStartElement("property"); writer.writeAttribute("name", "jnlp.packEnabled"); writer.writeAttribute("value", "true"); writer.writeEndElement(); writer.writeStartElement("j2se"); writer.writeAttribute("version", "1.6+"); writer.writeEndElement(); for (final File jar : jnlpFiles.getAllWebstartJars()) { writer.writeStartElement("jar"); writer.writeAttribute("href", jar.getName()); writer.writeAttribute("size", "" + jar.length()); writer.writeEndElement(); } writer.writeEndElement(); // resources writer.writeStartElement("application-desc"); writer.writeAttribute("main-class", "org.exist.client.InteractiveClient"); writer.writeStartElement("argument"); writer.writeCharacters("-ouri=" + startUrl); writer.writeEndElement(); writer.writeStartElement("argument"); writer.writeCharacters("--no-embedded-mode"); writer.writeEndElement(); if (request.isSecure()) { writer.writeStartElement("argument"); writer.writeCharacters("--use-ssl"); writer.writeEndElement(); } writer.writeEndElement(); // application-desc writer.writeEndElement(); // jnlp writer.writeEndDocument(); writer.flush(); writer.close(); } catch (final Throwable ex) { logger.error(ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } }
From source file:org.josso.liferay6.agent.LiferaySSOAgentFilter.java
@Override protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) request; HttpServletResponse hres = (HttpServletResponse) response; // URI pattern matching is implemented programmatically in case this filter is bound to the root web context // (i.e. '/*' url pattern) required for intercepting locale-prefixed URLs. if (!hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGIN_URI) && !hreq.getRequestURI().contains(LIFERAY_PORTAL_LOGOUT_URI) && !hreq.getRequestURI().contains(LIFERAY_GROUP_URI) && !hreq.getRequestURI().contains(LIFERAY_USER_URI) && !hreq.getRequestURI().contains(LIFERAY_WEB_URI) && !hreq.getRequestURI().contains(JOSSO_SECURITY_CHECK_URI)) { filterChain.doFilter(hreq, hres); return;/*from w ww.j a v a 2 s . c om*/ } if (log.isDebugEnabled()) log.debug("Processing : " + hreq.getContextPath()); try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); long companyId = PortalUtil.getCompanyId(request); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; if (!_agent.isPartnerApp(vhost, contextPath)) { filterChain.doFilter(hreq, hres); if (log.isDebugEnabled()) log.debug("Context is not a josso partner app : " + hreq.getContextPath()); return; } String nodeId = hreq.getParameter("josso_node"); if (nodeId != null) { if (log.isDebugEnabled()) log.debug("Storing JOSSO Node id : " + nodeId); _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId); } else { nodeId = _agent.getAttribute(hreq, "JOSSO_NODE"); if (log.isDebugEnabled()) log.debug("Found JOSSO Node id : " + nodeId); } // ------------------------------------------------------------------ // Check some basic HTTP handling // ------------------------------------------------------------------ // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath); if (cfg.isSendP3PHeader() && !hres.isCommitted()) { hres.setHeader("P3P", cfg.getP3PHeaderValue()); } // Get our session ... HttpSession session = hreq.getSession(true); // ------------------------------------------------------------------ // Check if the Liferay application required its login form [/c/portal/login] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGIN_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay login: '" + hreq.getRequestURI() + "'"); //save referer url in case the user clicked on Login from some public resource (page) //so agent can redirect the user back to that page after successful login if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) { saveLoginBackToURL(hreq, hres, session, true); } else { saveLoginBackToURL(hreq, hres, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } // ------------------------------------------------------------------ // Check if the Liferay application required its logout form [/c/portal/logout] // ------------------------------------------------------------------ if (JossoLiferayProps.isEnabled(companyId) && hreq.getRequestURI().endsWith(LIFERAY_PORTAL_LOGOUT_URI)) { if (log.isDebugEnabled()) log.debug("Requested liferay logout: '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (log.isDebugEnabled()) log.debug("Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(ssoCookie); // invalidate session (unbind josso security context) session.invalidate(); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); return; } // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking for SSO cookie"); Cookie cookie = null; Cookie cookies[] = hreq.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) { cookie = cookies[i]; break; } } String jossoSessionId = (cookie == null) ? null : cookie.getValue(); LiferayLocalSession localSession = new LiferayLocalSession(session); // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ if (log.isDebugEnabled()) { log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) { if (log.isDebugEnabled()) { log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'"); } LiferaySSOAgentRequest customAuthRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest( cfg.getId(), SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq, hres); _agent.processRequest(customAuthRequest); return; } if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("SSO cookie is not present, verifying optional login process "); // We have no cookie, remember me is enabled and a security check without assertion was received ... // This means that the user could not be identified ... go back to the original resource if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") == null) { if (log.isDebugEnabled()) log.debug(_agent.getJossoSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = getSavedRequestURL(hreq); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return; } // This is a standard anonymous request! if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) { if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } if (log.isDebugEnabled()) log.debug("SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log.debug("SSO cookie not present and relaying was not requested, skipping"); filterChain.doFilter(hreq, hres); return; } } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ if (_agent.isResourceIgnored(cfg, hreq)) { filterChain.doFilter(hreq, hres); return; } // This URI should be protected by SSO, go on ... if (log.isDebugEnabled()) log.debug("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Executing agent..."); // ------------------------------------------------------------------ // Check if a user has been authenitcated and should be checked by the agent. // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (log.isDebugEnabled()) log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); LiferaySSOAgentRequest relayRequest; if (log.isDebugEnabled()) log.debug("Outbound relaying requested for assertion id [" + assertionId + "]"); relayRequest = (LiferaySSOAgentRequest) doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(relayRequest); if (entry == null) { // This is wrong! We should have an entry here! log.error( "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found."); // Throw an exception and let the container send the INERNAL SERVER ERROR throw new ServletException("No Principal found. Verify your SSO Agent Configuration!"); } if (log.isDebugEnabled()) log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (log.isDebugEnabled()) log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]"); // The cookie is valid to for the partner application only ... in the future each partner app may // store a different auth. token (SSO SESSION) value cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure()); hres.addCookie(cookie); // Redirect the user to the original request URI (which will cause // the original request to be restored) String requestURI = getSavedSplashResource(hreq); if (requestURI == null) { requestURI = getSavedRequestURL(hreq); if (requestURI == null) { if (cfg.getDefaultResource() != null) { requestURI = cfg.getDefaultResource(); } else { // If no saved request is found, redirect to the partner app root : requestURI = hreq.getRequestURI().substring(0, (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length())); } // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?! String singlePointOfAccess = _agent.getSinglePointOfAccess(); if (singlePointOfAccess != null) { requestURI = singlePointOfAccess + requestURI; } else { String reverseProxyHost = hreq .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER); if (reverseProxyHost != null) { requestURI = reverseProxyHost + requestURI; } } if (log.isDebugEnabled()) log.debug("No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(hreq, hres); _agent.clearAutomaticLoginReferer(hreq, hres); _agent.prepareNonCacheResponse(hres); // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (log.isDebugEnabled()) log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); } return; } SSOAgentRequest r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession, null, hreq, hres); SingleSignOnEntry entry = _agent.processRequest(r); if (log.isDebugEnabled()) log.debug("Executed agent."); // Get session map for this servlet context. Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP); if (sessionMap.get(localSession.getWrapped()) == null) { // the local session is new so, make the valve listen for its events so that it can // map them to local session events. // Not supported : session.addSessionListener(this); sessionMap.put(session, localSession); } // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ if (log.isDebugEnabled()) log.debug("Process request for '" + hreq.getRequestURI() + "'"); if (entry != null) { if (log.isDebugEnabled()) log.debug("Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); } else { log.info("No Valid SSO Session, attempt an optional login?"); // This is a standard anonymous request! if (cookie != null) { // cookie is not valid cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure()); hres.addCookie(cookie); } if (cookie != null || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) { if (log.isDebugEnabled()) log.debug("SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequestURL(hreq, hres); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (log.isDebugEnabled()) log.debug("Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); return; } else { if (log.isDebugEnabled()) log.debug("SSO cookie is not present, but login optional process is not required"); } } // propagate the login and logout URLs to // partner applications. hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl()); hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl()); hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId); // ------------------------------------------------------------------ // Invoke the next Valve in our pipeline // ------------------------------------------------------------------ filterChain.doFilter(hreq, hres); } finally { if (log.isDebugEnabled()) log.debug("Processed : " + hreq.getContextPath()); } }
From source file:org.sakaiproject.util.RequestFilter.java
/** * Filter a request / response.//from ww w .ja v a2 s . c o m */ public void doFilter(ServletRequest requestObj, ServletResponse responseObj, FilterChain chain) throws IOException, ServletException { StringBuffer sb = null; long startTime = System.currentTimeMillis(); // bind some preferences as "current" Boolean curRemoteUser = (Boolean) ThreadLocalManager.get(CURRENT_REMOTE_USER); Integer curHttpSession = (Integer) ThreadLocalManager.get(CURRENT_HTTP_SESSION); String curContext = (String) ThreadLocalManager.get(CURRENT_CONTEXT); ServletRequest curRequest = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST); ServletResponse curResponse = (ServletResponse) ThreadLocalManager.get(CURRENT_HTTP_RESPONSE); boolean cleared = false; // keep track of temp files with this request that need to be deleted on the way out List<FileItem> tempFiles = new ArrayList<FileItem>(); try { ThreadLocalManager.set(CURRENT_REMOTE_USER, Boolean.valueOf(m_sakaiRemoteUser)); ThreadLocalManager.set(CURRENT_HTTP_SESSION, Integer.valueOf(m_sakaiHttpSession)); ThreadLocalManager.set(CURRENT_CONTEXT, m_contextId); // make the servlet context available ThreadLocalManager.set(CURRENT_SERVLET_CONTEXT, m_servletContext); // we are expecting HTTP stuff if (!((requestObj instanceof HttpServletRequest) && (responseObj instanceof HttpServletResponse))) { // if not, just pass it through chain.doFilter(requestObj, responseObj); return; } HttpServletRequest req = (HttpServletRequest) requestObj; HttpServletResponse resp = (HttpServletResponse) responseObj; // knl-640 // The AppDomain should reject: // 1) all GET URL's starting with contentPaths // // The FileDomain should only accept: // 1) any URL's in loginPath. We have to accept POST methods here // as well so folks can log in on this node. // 2) any GET URL's from contentPaths (POST's any other methods not // allowed. if (useContentHostingDomain) { String requestURI = req.getRequestURI(); if (req.getQueryString() != null) requestURI += "?" + req.getQueryString(); if (startsWithAny(requestURI, contentPaths) && "GET".equalsIgnoreCase(req.getMethod())) { if (!req.getServerName().equals(chsDomain) && !(startsWithAny(requestURI, contentExceptions))) { resp.sendRedirect(chsUrl + requestURI); return; } } else { if (req.getServerName().equals(chsDomain) && !(startsWithAny(requestURI, contentPaths) && !"GET".equalsIgnoreCase(req.getMethod())) && !(startsWithAny(requestURI, loginPaths))) { resp.sendRedirect(appUrl + requestURI); return; } } } // check on file uploads and character encoding BEFORE checking if // this request has already been filtered, as the character encoding // and file upload handling are configurable at the tool level. // so the 2nd invokation of the RequestFilter (at the tool level) // may actually cause character encoding and file upload parsing // to happen. // handle character encoding handleCharacterEncoding(req, resp); // handle file uploads req = handleFileUpload(req, resp, tempFiles); // if we have already filtered this request, pass it on if (req.getAttribute(ATTR_FILTERED) != null) { // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); chain.doFilter(req, resp); } // filter the request else { if (M_log.isDebugEnabled()) { sb = new StringBuffer("http-request: "); sb.append(req.getMethod()); sb.append(" "); sb.append(req.getRequestURL()); if (req.getQueryString() != null) { sb.append("?"); sb.append(req.getQueryString()); } M_log.debug(sb); } try { // mark the request as filtered to avoid re-filtering it later in the request processing req.setAttribute(ATTR_FILTERED, ATTR_FILTERED); // some useful info ThreadLocalManager.set(ServerConfigurationService.CURRENT_SERVER_URL, serverUrl(req)); // make sure we have a session Session s = assureSession(req, resp); // pre-process request req = preProcessRequest(s, req); // detect a tool placement and set the current tool session detectToolPlacement(s, req); // pre-process response resp = preProcessResponse(s, req, resp); // set the request and response for access via the thread local ThreadLocalManager.set(CURRENT_HTTP_REQUEST, req); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, resp); // set the portal into thread local if (m_contextId != null && m_contextId.length() > 0) { ThreadLocalManager.set(ServerConfigurationService.CURRENT_PORTAL_PATH, "/" + m_contextId); } // Only synchronize on session for Terracotta. See KNL-218, KNL-75. if (TERRACOTTA_CLUSTER) { synchronized (s) { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } } else { // Pass control on to the next filter or the servlet chain.doFilter(req, resp); // post-process response postProcessResponse(s, req, resp); } // Output client cookie if requested to do so if (s != null && req.getAttribute(ATTR_SET_COOKIE) != null) { // check for existing cookie String suffix = getCookieSuffix(); Cookie c = findCookie(req, cookieName, suffix); // the cookie value we need to use String sessionId = s.getId() + DOT + suffix; // set the cookie if necessary if ((c == null) || (!c.getValue().equals(sessionId))) { c = new Cookie(cookieName, sessionId); c.setPath("/"); c.setMaxAge(-1); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(resp, c); } } } catch (ClosingException se) { closingRedirect(req, resp); } catch (RuntimeException t) { M_log.error("", t); throw t; } catch (IOException ioe) { M_log.error("", ioe); throw ioe; } catch (ServletException se) { M_log.error(se.getMessage(), se); throw se; } finally { // clear any bound current values ThreadLocalManager.clear(); cleared = true; } } } finally { if (!cleared) { // restore the "current" bindings ThreadLocalManager.set(CURRENT_REMOTE_USER, curRemoteUser); ThreadLocalManager.set(CURRENT_HTTP_SESSION, curHttpSession); ThreadLocalManager.set(CURRENT_CONTEXT, curContext); ThreadLocalManager.set(CURRENT_HTTP_REQUEST, curRequest); ThreadLocalManager.set(CURRENT_HTTP_RESPONSE, curResponse); } // delete any temp files deleteTempFiles(tempFiles); if (M_log.isDebugEnabled() && sb != null) { long elapsedTime = System.currentTimeMillis() - startTime; M_log.debug("request timing (ms): " + elapsedTime + " for " + sb); } } }