List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl
@Deprecated
public String encodeRedirectUrl(String url);
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 va 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; } 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:com.bluexml.xforms.controller.navigation.NavigationManager.java
/** * Send XForms to Chiba filter.<br> * Inserts session id into form.<br> * No data manipulation has to be made here. * /*from ww w. j a v a 2 s . c o m*/ * @param req * the req * @param resp * the resp * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ public void sendXForms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); String sessionId = session.getId(); controller = getController(); String testStr = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_SERVE_TEST_PAGE.getText())); boolean serveTestPage = StringUtils.equals(testStr, "true"); String pageId = StringUtils.trimToNull(req.getParameter(PAGE_ID)); // called from a direct link? set our info (pageId, stackId) if (pageId == null) { // check for a possible initialisation call boolean isInit = StringUtils.equals(req.getParameter(MsgId.PARAM_INIT_CALL.getText()), "true"); if (isInit) { ServletOutputStream stream = resp.getOutputStream(); String result = (loadConfiguration(req, true) == -1) ? "success" : "failure"; stream.write(result.getBytes()); stream.close(); return; } pageId = NavigationSessionListener.getPageId(sessionId); NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId); // check whether reloading of the mapping.xml file was asked for if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_MAPPING_FILE.getText()), "true")) { controller.performDynamicReload(); } // check whether reloading of properties/configuration files was asked for if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_PROPERTIES.getText()), "true")) { int resLoad = loadConfiguration(req, false); if (logger.isDebugEnabled()) { if (resLoad == -1) { logger.debug("Reloaded properties: OK."); } else { String reason = ""; switch (resLoad) { case 0: reason = "an exception occured"; break; case 1: reason = "properties files"; break; case 2: reason = "redirection file"; break; } logger.debug("Failed in loading the configuration. Reason: " + reason); } } } // set specific CSS if given this.setCssUrl(req); // initial status message. CAUTION: may be overridden later in case of errors. String statusMsg = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_STATUS_MSG.getText())); if (statusMsg != null) { navigationPath.setStatusMsg(statusMsg); } // deal with standalone mode if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "true")) { controller.setStandaloneMode(true); } if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "false")) { controller.setStandaloneMode(false); } PageInfoBean pageInfo = collectPageInfo(req); // save session and URL we were called with (useful when a host is multi-domain'ed) String curServletURL = this.registerSessionURL(req, sessionId); // remember where we are navigationPath.setCurrentPage(pageInfo); String location = curServletURL + "?pageId=" + pageId + "&stackId=" + navigationPath.getSize(); // propagate queryString location += "&" + req.getQueryString(); if (serveTestPage == false) { // redirect the web client, providing ids we need resp.sendRedirect(resp.encodeRedirectURL(location)); return; } } // the ids are available NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId); if (navigationPath.isEmpty()) { // the servlet is called directly with ids we did not register throw new ServletException(MsgPool.getMsg(MsgId.MSG_SESSION_TIMED_OUT)); } Page currentPage = navigationPath.peekCurrentPage(); // set the warning if page was called with an object it can't display if (currentPage.isWrongCallType()) { navigationPath.setStatusMsg("WARNING: the data Id provided is not appropriate for this form."); } // get the form template as a string String statusDisplayedMsg = navigationPath.getStatusDisplayedMsg(); Document doc = loadXFormsDocument(req, sessionId, pageId, statusDisplayedMsg, currentPage); req.setAttribute(WebFactory.XFORMS_NODE, doc); resp.getOutputStream().close(); }
From source file:org.sensorhub.impl.security.gxoauth.OAuthAuthenticator.java
@Override public Authentication validateRequest(ServletRequest req, ServletResponse resp, boolean mandatory) throws ServerAuthException { try {//from www. ja v a 2s.c om HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String redirectUrl = config.redirectURL != null ? config.redirectURL : request.getRequestURL().toString(); HttpSession session = request.getSession(true); // check for cached auth Authentication cachedAuth = (Authentication) session .getAttribute(SessionAuthentication.__J_AUTHENTICATED); if (cachedAuth != null && cachedAuth instanceof Authentication.User) { if (!_loginService.validate(((Authentication.User) cachedAuth).getUserIdentity())) session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED); else return cachedAuth; } // if calling back from provider with auth code if (generatedState != null && request.getParameter(OAuth.OAUTH_CODE) != null) { try { // first request temporary access token OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request); String code = oar.getCode(); log.debug("OAuth Code = " + code); // check state parameter if (!generatedState.equals(oar.getState())) throw OAuthProblemException.error("Invalid state parameter"); OAuthClientRequest authRequest = OAuthClientRequest.tokenLocation(config.tokenEndpoint) .setCode(code).setRedirectURI(redirectUrl).setGrantType(GrantType.AUTHORIZATION_CODE) .buildBodyMessage(); String authString = config.clientID + ":" + config.clientSecret; byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); authRequest.addHeader("Authorization", "Basic " + authStringEnc); authRequest.addHeader("Accept", "application/json"); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(authRequest, HttpMethod.POST); // read access token and store in session String accessToken = oAuthResponse.getAccessToken(); log.debug("OAuth Token = " + accessToken); // request user info OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(config.userInfoEndpoint) .setAccessToken(accessToken).buildQueryMessage(); bearerClientRequest.addHeader("Authorization", accessToken); OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, HttpMethod.GET, OAuthResourceResponse.class); // parse user info log.debug("UserInfo = " + resourceResponse.getBody()); JsonReader jsonReader = new JsonReader(new StringReader(resourceResponse.getBody())); String userId = parseUserInfoJson(jsonReader); // login and return UserAuth object UserIdentity user = login(userId, "NONE", req); if (user != null) { UserAuthentication userAuth = new UserAuthentication(getAuthMethod(), user); session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, userAuth); return userAuth; } response.sendError(HttpServletResponse.SC_FORBIDDEN); return Authentication.SEND_FAILURE; } catch (OAuthProblemException | OAuthSystemException | IOException e) { log.error("Cannot complete authentication at endpoint " + config.tokenEndpoint, e); response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return Authentication.SEND_FAILURE; } } // first login at auth provider else { try { // generate request to auth provider this.generatedState = UUID.randomUUID().toString(); OAuthClientRequest authRequest = OAuthClientRequest.authorizationLocation(config.authzEndpoint) .setClientId(config.clientID).setRedirectURI(redirectUrl) .setResponseType(OAuth.OAUTH_CODE).setScope(config.authzScope).setState(generatedState) .buildQueryMessage(); // send as redirect String loginUrl = authRequest.getLocationUri(); response.sendRedirect(response.encodeRedirectURL(loginUrl)); return Authentication.SEND_CONTINUE; } catch (OAuthSystemException e) { log.error("Cannot redirect to authentication endpoint " + config.authzEndpoint, e); response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return Authentication.SEND_FAILURE; } } } catch (IOException e) { log.error("Cannot send HTTP error", e); return Authentication.SEND_FAILURE; } }
From source file:org.guanxi.sp.sakai.portal.tool.GuanxiPortal.java
/** * Main entry point for the Shibboleth portal. It' here that we register a Pod for the current user. * By the time we get here, the full Shibboleth protocol has been completed and the Guanxi Guard * has created a Guanxi Pod for the user and stored it in the servlet context. * * @param request Standard HttpServletRequest * @param response Standard HttpServletResponse * @throws ServletException if an error occurs * @throws IOException if an error occurs *//*from w w w .j a v a 2 s . c o m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // make sure the portal is enabled if (!ServerConfigurationService.getString(SHIBB_ENABLED_KEY, "false").equalsIgnoreCase("true")) { log.error("Shibboleth portal disabled"); doError(request, response, "Disabled", "The Shibboleth Portal is currently disabled. To enable this, set \"shibb.enabled=true\" in your sakai.properties file."); return; } // Configuration sanity checks if (!sanityCheck()) { log.error("Sanity check failed"); doError(request, response, "SAML Attribute configuration error", "Please check your saml.attribute.name settings in sakai.properties."); return; } // Get a Sakai Pod ready... GSKPod gxPod = null; // ...and search the request for the Guanxi Guard cookie which will point to the Guanxi Pod Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { if (cookies[c].getName() .equals(getServletContext().getAttribute(Guanxi.CONTEXT_ATTR_GUARD_COOKIE_NAME))) { Pod pod = (Pod) getServletContext().getAttribute(cookies[c].getValue()); if (pod != null) { String podErrors = verifyPod(pod); if (!podErrors.equals("")) { doError(request, response, "Shibboleth", podErrors); return; } // If the eid attribute is multi-valued, use the first one String eid = pod.getBag() .getAttributeValue(ServerConfigurationService.getString(EID_ATTRIBUTE)); if (eid.indexOf(Bag.ATTR_VALUE_DELIM) != -1) { eid = eid.split(Bag.ATTR_VALUE_DELIM)[0]; } // Register the Sakai pod with this eid gxPod = podManager.registerPod(eid); // Update the user's details in the Sakai pod according to their attributes gxPod.setFirstName(pod.getBag() .getAttributeValue(ServerConfigurationService.getString(FIRSTNAME_ATTRIBUTE))); gxPod.setLastName(pod.getBag() .getAttributeValue(ServerConfigurationService.getString(SURNAME_ATTRIBUTE))); gxPod.setEmail(pod.getBag() .getAttributeValue(ServerConfigurationService.getString(EMAIL_ATTRIBUTE))); /* Save the raw SAML response in the Sakai pod. This is the response from the * Shibboleth Attribute Authority and contains the attributes in their raw * SAML form. It's stored in the pod as a String. */ gxPod.setSAMLResponse(pod.getBag().getSamlResponse()); // Sakai will deal with logout so delete the Guanxi Guard cookie... cookies[c].setMaxAge(0); response.addCookie(cookies[c]); // ...and remove the Guanxi Guard Pod getServletContext().setAttribute(cookies[c].getValue(), null); } // if (pod != null) } // if (cookies[c].getName().startsWith ... } // for (int c = 0; c < cookies.length; c++) } // if (cookies != null) // If we didn't get a pod for them, go to the error page if (gxPod == null) { doError(request, response, "Shibboleth error", "We could not find your Shibboleth credentials."); return; } // Get the current session Session session = (SessionManager.getCurrentSession() == null) ? SessionManager.startSession() : SessionManager.getCurrentSession(); /* As the user has been through the Shibboleth process we can trust them as we trust * their IdP to issue assertions on their behalf. So what we see in the attributes * should be a valid representation of the user. */ ExternalTrustedEvidence trustedUser = new ExternalTrustedEvidence(gxPod.getEid()); // Log them in and redirect to the requested resource Authentication authentication = AuthenticationManager.authenticate(trustedUser); if (UsageSessionService.login(authentication, request)) { session.setActive(); String defaultPortal = ServerConfigurationService.getServerUrl() + ServerConfigurationService.getString(DEFAULT_PORTAL_REDIRECT_KEY); response.sendRedirect(response.encodeRedirectURL(defaultPortal)); } else { doError(request, response, "Shibboleth error", "We could not log you in."); } } catch (Throwable t) { doThrowableError(request, response, t); } }
From source file:org.jahia.bin.Logout.java
protected void doRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException { String redirect = request.getParameter("redirect"); if (redirect == null) { redirect = request.getHeader("referer"); if (StringUtils.isNotEmpty(redirect) && Login.isAuthorizedRedirect(request, redirect, false)) { redirect = redirect.startsWith("http://") ? StringUtils.substringAfter(redirect, "http://") : StringUtils.substringAfter(redirect, "https://"); redirect = redirect.contains("/") ? "/" + StringUtils.substringAfter(redirect, "/") : null; } else {//from w w w.j a v a 2s. c om redirect = null; } } else if (!Login.isAuthorizedRedirect(request, redirect, false)) { redirect = null; } if (StringUtils.isNotBlank(redirect)) { try { final String r = redirect; HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) { @Override public String getRequestURI() { return r; } @Override public String getPathInfo() { if (r.startsWith(getContextPath() + "/cms/")) { return StringUtils.substringAfter(r, getContextPath() + "/cms"); } return null; } }; if (urlRewriteService.prepareInbound(wrapper, response)) { RewrittenUrl restored = urlRewriteService.rewriteInbound(wrapper, response); if (restored != null) { redirect = request.getContextPath() + restored.getTarget(); } } } catch (Exception e) { logger.error("Cannot rewrite redirection url", e); } String prefix = request.getContextPath() + "/cms/"; if (redirect.startsWith(prefix)) { String url = "/" + StringUtils.substringAfter(redirect, prefix); String hash = StringUtils.substringAfterLast(url, "#"); url = StringUtils.substringBefore(url, ";" + SettingsBean.getInstance().getJsessionIdParameterName()); url = StringUtils.substringBefore(url, "?"); url = StringUtils.substringBefore(url, "#"); if (hash != null && hash.startsWith("/sites/") && url.contains("/sites/")) { url = StringUtils.substringBefore(url, "/sites/") + StringUtils.substringBefore(hash, ":") + ".html"; } List<String> urls = new ArrayList<String>(); urls.add(url); if (url.startsWith("/edit/")) { url = "/render/" + StringUtils.substringAfter(url, "/edit/"); urls.add(url); } else if (url.startsWith("/editframe/default/")) { url = "/render/live/" + StringUtils.substringAfter(url, "/editframe/default/"); urls.add(url); } else if (url.startsWith("/contribute/")) { url = "/render/" + StringUtils.substringAfter(url, "/contribute/"); urls.add(url); } else if (url.startsWith("/contributeframe/default/")) { url = "/render/live/" + StringUtils.substringAfter(url, "/contributeframe/default/"); urls.add(url); } if (url.startsWith("/render/default/")) { url = "/render/live/" + StringUtils.substringAfter(url, "/render/default/"); urls.add(url); } for (String currentUrl : urls) { try { URLResolver r = urlResolverFactory.createURLResolver(currentUrl, request.getServerName(), request); if (r.getPath().startsWith("/sites/")) { JCRNodeWrapper n = r.getNode(); // test that we do not get the site node, in that case, redirect to homepage if (n.isNodeType("jnt:virtualsite")) { n = ((JCRSiteNode) n).getHome(); } if (n == null) { // this can occur if the homepage of the site is not set redirect = request.getContextPath() + "/"; } else { redirect = prefix + r.getServletPart() + "/" + r.getWorkspace() + "/" + resolveLanguage(request, n.getResolveSite()) + n.getPath() + ".html"; } } else { redirect = request.getContextPath() + "/"; } redirect = urlRewriteService.rewriteOutbound(redirect, request, response); response.sendRedirect(response.encodeRedirectURL(redirect)); return; } catch (Exception e) { logger.debug("Cannot redirect to " + currentUrl, e); } } response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/")); return; } } response.sendRedirect(response .encodeRedirectURL(StringUtils.isNotEmpty(redirect) ? redirect : request.getContextPath() + "/")); }
From source file:at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet.java
/** * Verifies the identity link and responds with a new * <code>CreateXMLSignatureRequest</code>. * <br>/*from w w w. j av a 2 s . c o m*/ * Request parameters: * <ul> * <li>MOASessionID: ID of associated authentication session</li> * <li>XMLResponse: <code><InfoboxReadResponse></code></li> * </ul> * Response: * <ul> * <li>Content type: <code>"text/xml"</code></li> * <li>Content: see return value of {@link AuthenticationServer#verifyIdentityLink}</li> * <li>Error status: <code>500</code> * </ul> * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("POST GetForeignIDServlet"); Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); Map<String, String> parameters; String pendingRequestID = null; try { parameters = getParameters(req); } catch (FileUploadException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); throw new IOException(e.getMessage()); } String sessionID = req.getParameter(PARAM_SESSIONID); pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); String redirectURL = null; AuthenticationSession session = null; try { String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE); // check parameter if (!ParamValidatorUtils.isValidSessionID(sessionID)) throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); session = AuthenticationServer.getSession(sessionID); //change MOASessionID sessionID = AuthenticationSessionStoreage.changeSessionID(session); Logger.debug(xmlCreateXMLSignatureResponse); CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse) .parseResponseDsig(); try { String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature()); session.setAuthBlock(serializedAssertion); } catch (TransformerException e) { throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); } catch (IOException e) { throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); } Element signature = csresp.getDsigSignature(); try { session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); } catch (CertificateException e) { Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); throw new MOAIDException("auth.14", null); } // make SZR request to the identity link CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature); if (null != response.getErrorResponse()) { // TODO fix exception parameter throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(), (String) response.getErrorResponse().getInfo()); } else { IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser( new ByteArrayInputStream(response.getIdentityLink())); IdentityLink identitylink = ilParser.parseIdentityLink(); session.setIdentityLink(identitylink); //set QAA Level four in case of card authentifcation session.setQAALevel(PVPConstants.STORK_QAA_1_4); String samlArtifactBase64 = AuthenticationServer.getInstance() .getForeignAuthenticationData(session); //session is implicit stored in changeSessionID!!!! String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); Logger.info("Daten angelegt zu MOASession " + newMOASessionID); if (!samlArtifactBase64.equals("Redirect to Input Processor")) { /*redirectURL = session.getOAURLRequested(); if (!session.getBusinessService()) { redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); } redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); redirectURL = resp.encodeRedirectURL(redirectURL);*/ redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), newMOASessionID); redirectURL = resp.encodeRedirectURL(redirectURL); } else { redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, newMOASessionID); } try { AuthenticationSessionStoreage.storeSession(session); } catch (MOADatabaseException e) { throw new MOAIDException("Session store error", null); } resp.setContentType("text/html"); resp.setStatus(302); resp.addHeader("Location", redirectURL); Logger.debug("REDIRECT TO: " + redirectURL); } } catch (MOAIDException ex) { handleError(null, ex, req, resp, pendingRequestID); } catch (Exception e) { Logger.error("GetForeignIDServlet has an interal Error.", e); } }
From source file:at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet.java
private void handleSignResponse(HttpServletRequest request, HttpServletResponse response) { Logger.info("handleSignResponse started"); String moaSessionID = request.getParameter("moaSessionID"); String signResponse = request.getParameter("signresponse"); Logger.info("moaSessionID:" + moaSessionID); Logger.info("signResponse:" + signResponse); String pendingRequestID = null; try {/*from w w w. j av a 2 s . co m*/ //load MOASession from database AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID); //change MOASessionID moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); Logger.info("pendingRequestID:" + pendingRequestID); String signResponseString = new String(Base64.decodeBase64(signResponse), "UTF8"); Logger.info("RECEIVED signresponse:" + signResponseString); //create SignResponse object Source response1 = new StreamSource(new java.io.StringReader(signResponseString)); SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class); // SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(Base64.signResponse))); String citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse); // memorize signature into authblock moaSession.setAuthBlock(citizenSignature); X509Certificate cert = getSignerCertificate(citizenSignature); moaSession.setSignerCertificate(cert); VerifyXMLSignatureResponse xMLVerifySignatureResponse = verifyXMLSignature(citizenSignature); at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse tmp = convert(xMLVerifySignatureResponse); moaSession.setXMLVerifySignatureResponse(tmp); try { IPersonalAttributeList personalAttributeList = moaSession .getAuthnResponseGetPersonalAttributeList(); //Add SignResponse TODO Add signature (extracted from signResponse)? List<String> values = new ArrayList<String>(); values.add(signResponseString); // values.add(citizenSignature); Logger.debug("Assembling signedDoc attribute"); PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, "Available"); personalAttributeList.add(signedDocAttribute); String authnContextClassRef = moaSession.getAuthnContextClassRef(); SZRGInsertion(moaSession, personalAttributeList, authnContextClassRef, citizenSignature); } catch (STORKException e) { // this is really nasty but we work against the system here. We are supposed to get the gender attribute from // stork. If we do not, we cannot register the person in the ERnP - we have to have the // gender for the represented person. So here comes the dirty hack. if (e.getCause() instanceof STORKException && e.getCause().getMessage().equals("gender not found in response")) { try { Logger.trace("Initialize VelocityEngine..."); VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html"); VelocityContext context = new VelocityContext(); context.put("SAMLResponse", request.getParameter("SAMLResponse")); context.put("action", request.getRequestURL()); StringWriter writer = new StringWriter(); template.merge(context, writer); response.getOutputStream().write(writer.toString().getBytes("UTF-8")); } catch (Exception e1) { Logger.error("Error sending gender retrival form.", e1); // httpSession.invalidate(); throw new MOAIDException("stork.10", null); } return; } Logger.error("Error connecting SZR Gateway", e); throw new MOAIDException("stork.10", null); } Logger.debug("Add full STORK AuthnResponse to MOA session"); moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));//TODO ask Florian/Thomas authnResponse? moaSession.setForeigner(true); //session is implicit stored in changeSessionID!!!! String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID); //redirect String redirectURL = null; redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID), newMOASessionID); redirectURL = response.encodeRedirectURL(redirectURL); response.sendRedirect(redirectURL); Logger.info("REDIRECT TO: " + redirectURL); } catch (AuthenticationException e) { handleError(null, e, request, response, pendingRequestID); } catch (MOAIDException e) { handleError(null, e, request, response, pendingRequestID); } catch (Exception e) { Logger.error("PEPSConnector has an interal Error.", e); } finally { ConfigurationDBUtils.closeSession(); } }
From source file:de.zib.scalaris.examples.wikipedia.bliki.WikiServlet.java
/** * Shows a preview of the edit operation submitted or saves the page with * the given <tt>title</tt> depending on what button the user clicked. * /*from w w w . j a v a 2s. co m*/ * @param request * the request of the current operation * @param response * the response of the current operation * @param title * the title of the article to show * @param page * the bean for the page * * @throws IOException * @throws UnsupportedEncodingException * @throws ServletException */ private void handleEditPageSubmitted(HttpServletRequest request, HttpServletResponse response, String title, Connection connection, WikiPageEditBean page) throws UnsupportedEncodingException, IOException, ServletException { String content = request.getParameter("wpTextbox1"); String summary = request.getParameter("wpSummary"); int oldVersion = parseInt(request.getParameter("oldVersion"), -1); boolean minorChange = Boolean.parseBoolean(request.getParameter("minor")); // save page or preview+edit page? if (request.getParameter("wpSave") != null) { // save page Contributor contributor = new Contributor(); contributor.setIp(request.getRemoteAddr()); String timestamp = Revision.calendarToString(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); Revision newRev = new Revision(-1, timestamp, minorChange, contributor, summary); newRev.setUnpackedText(content); SavePageResult result; int retries = 0; while (true) { result = savePage(connection, title, newRev, oldVersion, null, siteinfo, "", namespace); page.addStats(result.stats); page.getInvolvedKeys().addAll(result.involvedKeys); if (!result.failedKeys.isEmpty()) { page.getFailedKeys().put(retries + 1, result.failedKeys); } if (!result.success && retries < Options.getInstance().WIKI_SAVEPAGE_RETRIES) { // check for conflicting edit on same page, do not retry in this case final Page oldPage = result.oldPage; if (oldPage != null && oldPage.getCurRev().getId() != oldVersion) { break; } try { Thread.sleep(Options.getInstance().WIKI_SAVEPAGE_RETRY_DELAY); } catch (InterruptedException e) { } ++retries; } else { break; } } page.setSaveAttempts(retries + 1); for (WikiEventHandler handler : eventHandlers) { handler.onPageSaved(page, result, connection); } if (result.success) { // successfully saved -> show page with a notice of the successful operation // also actively update the bloom filter of existing pages existingPages.add(NormalisedTitle.fromUnnormalised(title, namespace)); ArrayList<Long> times = new ArrayList<Long>(); for (List<Long> time : page.getStats().values()) { times.addAll(time); } // do not include the UTF-8-title directly into encodeRedirectURL since that's not // encoding umlauts (maybe other special chars as well) correctly, e.g. -> %E4 instead of %C3%A4 StringBuilder redirectUrl = new StringBuilder(256); redirectUrl.append("?title="); redirectUrl.append(URLEncoder.encode(title, "UTF-8")); redirectUrl.append("¬ice=successfully%20saved%20page"); redirectUrl.append("&save_times=" + StringUtils.join(times, "%2C")); redirectUrl.append("&save_attempts=" + page.getSaveAttempts()); for (Entry<Integer, List<String>> failedKeys : page.getFailedKeys().entrySet()) { redirectUrl.append("&failed_keys" + failedKeys.getKey() + "=" + URLEncoder.encode(StringUtils.join(failedKeys.getValue(), " # "), "UTF-8")); } redirectUrl.append("&involved_keys=" + URLEncoder.encode(StringUtils.join(page.getInvolvedKeys(), " # "), "UTF-8")); redirectUrl.append("&server_time=" + (System.currentTimeMillis() - page.getStartTime())); if (result.newPage.isRedirect()) { redirectUrl.append("&redirect=no"); } final String serviceUser = page.getServiceUser().isEmpty() ? "" : "&service_user=" + page.getServiceUser(); response.sendRedirect( "http://" + Options.getInstance().SERVERNAME + Options.getInstance().SERVERPATH + response.encodeRedirectURL(redirectUrl.toString()) + serviceUser); return; } else { // set error message and show the edit page again (see below) if (result.connect_failed) { setParam_error(request, "ERROR: DB connection failed"); } else { setParam_error(request, "ERROR: conflicting edit"); } addToParam_notice(request, "error: could not save page: <pre>" + result.message + "</pre>"); } } // preview+edit page page.setNotice(getParam_notice(request)); // set the textarea's contents: page.setPage(StringEscapeUtils.escapeHtml(content)); MyWikiModel wikiModel = getWikiModel(connection, page); String[] titleParts = wikiModel.splitNsTitle(title); wikiModel.setNamespaceName(titleParts[0]); wikiModel.setPageName(titleParts[1]); page.setPreview(wikiModel.renderPageWithCache(content)); page.setIncludes(wikiModel.getIncludes()); page.setTemplates(wikiModel.getTemplatesNoMagicWords()); page.addStats(wikiModel.getStats()); page.getInvolvedKeys().addAll(wikiModel.getInvolvedKeys()); page.setPage(content); page.setVersion(oldVersion); page.setError(getParam_error(request)); page.setTitle(title); page.setSummary(request.getParameter("wpSummary")); page.setWikiTitle(siteinfo.getSitename()); page.setWikiNamespace(namespace); forwardToPageJsp(request, response, connection, page, "pageEdit.jsp"); }
From source file:org.apache.catalina.authenticator.FormAuthenticator.java
/** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has been satisfied, or <code>false</code> if we have * created a response challenge already. * * @param request Request we are processing * @param response Response we are creating * @param config Login configuration describing how authentication * should be performed// ww w .j av a 2 s.co m * * @exception IOException if an input/output error occurs */ public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException { // References to objects we will need later HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); Session session = null; // Have we already authenticated someone? Principal principal = hreq.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) log.debug("Already authenticated '" + principal.getName() + "'"); // Associate the session with any existing SSO session if (ssoId != null) associate(ssoId, getSession(request, true)); return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); // Try to reauthenticate using data cached by SSO. If this fails, // either the original SSO logon was of DIGEST or SSL (which // we can't reauthenticate ourselves because there is no // cached username and password), or the realm denied // the user's reauthentication for some reason. // In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) return true; } // Have we authenticated this user before but have caching disabled? if (!cache) { session = getSession(request, true); if (log.isDebugEnabled()) log.debug("Checking for reauthenticate in session " + session); String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE); String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE); if ((username != null) && (password != null)) { if (log.isDebugEnabled()) log.debug("Reauthenticating username '" + username + "'"); principal = context.getRealm().authenticate(username, password); if (principal != null) { session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); register(request, response, principal, Constants.FORM_METHOD, username, password); return (true); } if (log.isDebugEnabled()) log.debug("Reauthentication failed, proceed normally"); } } // Is this the re-submit of the original request URI after successful // authentication? If so, forward the *original* request instead. if (matchRequest(request)) { session = getSession(request, true); if (log.isDebugEnabled()) log.debug("Restore request from session '" + session.getId() + "'"); principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE); register(request, response, principal, Constants.FORM_METHOD, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (String) session.getNote(Constants.SESS_PASSWORD_NOTE)); if (restoreRequest(request, session)) { if (log.isDebugEnabled()) log.debug("Proceed to restored request"); return (true); } else { if (log.isDebugEnabled()) log.debug("Restore of original request failed"); hres.sendError(HttpServletResponse.SC_BAD_REQUEST); return (false); } } // Acquire references to objects we will need to evaluate MessageBytes uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); String contextPath = hreq.getContextPath(); String requestURI = request.getDecodedRequestURI(); response.setContext(request.getContext()); // Is this the action request from the login page? boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION); // No -- Save this request and redirect to the form login page if (!loginAction) { session = getSession(request, true); if (log.isDebugEnabled()) log.debug("Save request in session '" + session.getId() + "'"); saveRequest(request, session); RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getLoginPage()); try { disp.forward(hreq, hres); response.finishResponse(); } catch (Throwable t) { log.warn("Unexpected error forwarding to login page", t); } return (false); } // Yes -- Validate the specified credentials and redirect // to the error page if they are not correct Realm realm = context.getRealm(); String username = hreq.getParameter(Constants.FORM_USERNAME); String password = hreq.getParameter(Constants.FORM_PASSWORD); if (log.isDebugEnabled()) log.debug("Authenticating username '" + username + "'"); principal = realm.authenticate(username, password); if (principal == null) { RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getErrorPage()); try { disp.forward(hreq, hres); } catch (Throwable t) { log.warn("Unexpected error forwarding to error page", t); } return (false); } // Save the authenticated Principal in our session if (log.isDebugEnabled()) log.debug("Authentication of '" + username + "' was successful"); if (session == null) session = getSession(request, true); session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); // If we are not caching, save the username and password as well if (!cache) { session.setNote(Constants.SESS_USERNAME_NOTE, username); session.setNote(Constants.SESS_PASSWORD_NOTE, password); } // Redirect the user to the original request URI (which will cause // the original request to be restored) requestURI = savedRequestURL(session); if (log.isDebugEnabled()) log.debug("Redirecting to original '" + requestURI + "'"); if (requestURI == null) hres.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin")); else hres.sendRedirect(hres.encodeRedirectURL(requestURI)); return (false); }
From source file:org.josso.gl2.agent.SSOAgentValve.java
/** * Perform single-sign-on support processing for this request. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @throws IOException if an input/output error occurs * @throws ServletException if a servlet error occurs *///from w ww .j a va 2 s. co m public int invoke(Request request, Response response) throws IOException, ServletException { // If this is not an HTTP request and response, just pass them on int ret = 0; if (!(request instanceof HttpRequest) || !(response instanceof HttpResponse)) { //context.invokeNext(request, response); ret = Valve.INVOKE_NEXT; return ret; } HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); if (debug >= 1) log("***Processing : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] path=" + hreq.getPathInfo()); try { container = (Container) request.getContext(); } catch (Exception e) { log("Erreur sur cast container", e); } try { // ------------------------------------------------------------------ // Check with the agent if this context should be processed. // ------------------------------------------------------------------ String contextPath = hreq.getContextPath(); String vhost = hreq.getServerName(); _agent.setCatalinaContainer(container); // In catalina, the empty context is considered the root context if ("".equals(contextPath)) contextPath = "/"; // T1 si l'appli n'est pas partenaire alors pas de SSO on continue if (!_agent.isPartnerApp(vhost, contextPath)) { if (debug >= 1) log("T1 Context is not a josso partner app : " + hreq.getContextPath()); hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte"); ret = Valve.END_PIPELINE; return ret; } else { log("T1 Context IS a josso partner app =" + hreq.getContextPath()); } // T2 ------------------------------------------------------------------ // 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()); } // ------------------------------------------------------------------ // Check if this URI is subject to SSO protection // ------------------------------------------------------------------ //T9 if (isResourceIgnored(cfg, request)) { log("T9 ressource non ssois (accs libre)"); ret = Valve.INVOKE_NEXT; return ret; } // Get our session ... session = getSession(((HttpRequest) request), true); testCookieSession(hreq); //T3 on revient aprs authentification russie et pour finalisation if (_agent.isSSOIDloged(jossoSessionId)) { iBoucle++; log("T3 SSOAgentValve Info retour authentifi pour " + jossoSessionId + " faire retour vers " + theOriginal); //********************************************************************************************** localSession = new CatalinaLocalSession(session); //T4 on revrifie ma prsence d'une entre SSOID SSOAgentRequest r = new CatalinaSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT, jossoSessionId, localSession); SingleSignOnEntry entry = _agent.processRequest(r); if (debug == 1) log("T3 Executed agent acction ACTION_ESTABLISH_SECURITY_CONTEXT"); // ------------------------------------------------------------------ // Has a valid user already been authenticated? // ------------------------------------------------------------------ //T3-1 if (entry != null) { if (debug == 1) log("T3-1 Principal '" + entry.principal + "' has already been authenticated"); // TODO : Not supported // (request).setAuthType(entry.authType); // (request).setUserPrincipal(entry.principal); //T3-2 } else { log("T3-2 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(), "-"); hres.addCookie(cookie); } //T3-2-1 if (cookie != null || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) { if (debug == 1) log("T3-2-1 SSO Session is not valid, attempting automatic login"); // Save current request, so we can co back to it later ... log("T3-2-1 ***On sauve la requte 2 ***"); saveRequest((HttpRequest) request, session); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (debug == 1) log("T3-2-1 Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); ret = Valve.INVOKE_NEXT; return ret; } else { if (debug == 1) log("T3-2-1 SSO cookie is not present, but login optional process is not required"); } } try { log("Avant sur webProgrammaticLogin -------------" + iBoucle); if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) { log("Erreur sur webProgrammaticLogin"); } else { log("Russite sur webProgrammaticLogin"); } log("Aprs sur webProgrammaticLogin-------------" + iBoucle); } catch (Exception err) { log("SSOAgentValve Erreur2 finalisation contexte securit", err); throw err; } // 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); //hres.sendRedirect(theOriginal); System.out.println("**********************Termin**********************"); ret = Valve.INVOKE_NEXT; return ret; } else { log("T3 SSOAgentValve Info retour pas authentifi pour " + jossoSessionId); iBoucle = 0; } String username = processAuthorizationToken(hreq); //TA2 //equivalent la page de login si pas autoris on passe par l'authent if (username == null && getSavedRequestURL(session) == null && !hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri()) && !hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) { log("TA2 Il faut une authentification pralable (premire URL)! session=" + session.getId()); //return sendAuthenticateChallenge(msgInfo); //return sendAuthenticateChallenge2(msgInfo); saveRequest((HttpRequest) request, session); theOriginal = getSavedRequestURL(session); hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); //response.setHeader("Location", jeVeux); hres.sendRedirect(hreq.getContextPath() + "/josso_login/"); ret = Valve.END_PIPELINE; return ret; } //T4 // ------------------------------------------------------------------ // Check if the partner application required the login form // ------------------------------------------------------------------ if (debug >= 1) log("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'"); // /josso_login/ ou /josso_user_login/ c'est pas la page de login qui fait cela ? if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri()) || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) { if (debug >= 1) log("T4 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, session, true); } else { saveLoginBackToURL(hreq, session, false); } String loginUrl = _agent.buildLoginUrl(hreq); if (debug >= 1) log("T4 Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); //question on termine ou on continue ret = Valve.END_PIPELINE; return ret; } //T5 // ------------------------------------------------------------------ // Check if the partner application required a logout // ------------------------------------------------------------------ if (debug >= 1) log("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) { if (debug >= 1) log("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'"); String logoutUrl = _agent.buildLogoutUrl(hreq, cfg); if (debug >= 1) log("T5 Redirecting to logout url '" + logoutUrl + "'"); // Clear previous COOKIE ... Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-"); hres.addCookie(ssoCookie); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(logoutUrl)); ret = Valve.END_PIPELINE; return ret; } //T6 // ------------------------------------------------------------------ // Check for the single sign on cookie // ------------------------------------------------------------------ testCookieSession(hreq); if (debug >= 1) log("T6 Session is: " + session); //localSession = new CatalinaLocalSession(session); //T7 // ------------------------------------------------------------------ // Check if the partner application submitted custom login form // ------------------------------------------------------------------ // /josso_authentication/ if (debug >= 1) { log("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'"); } if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) { if (debug >= 1) log("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'"); HttpSSOAgentRequest customAuthRequest = new HttpSSOAgentRequest( SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession); customAuthRequest.setRequest(hreq); customAuthRequest.setResponse(hres); customAuthRequest.setContext(request.getContext()); _agent.processRequest(customAuthRequest); ret = Valve.INVOKE_NEXT; return ret; } //T8 // si pas de cookie de session SSO if (cookie == null || cookie.getValue().equals("-")) { // ------------------------------------------------------------------ // Trigger LOGIN OPTIONAL if required // ------------------------------------------------------------------ if (debug >= 1) log("T8 SSO cookie is not present, verifying optional login process "); //T8-1 /josso_security_check // 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 (debug >= 1) log("T8-1 " + _agent.getJOSSOSecurityCheckUri() + " received without assertion. Login Optional Process failed"); String requestURI = this.getSavedRequestURL(session); _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); ret = Valve.INVOKE_NEXT; return ret; } //T8-2 // 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 (!isResourceIgnored(cfg, request) && _agent.isAutomaticLoginRequired(hreq)) { if (debug >= 1) log("T8-2 SSO cookie is not present, attempting automatic login"); // Save current request, so we can co back to it later ... saveRequest((HttpRequest) request, session); String loginUrl = _agent.buildLoginOptionalUrl(hreq); if (debug >= 1) log("T8-2 Redirecting to login url '" + loginUrl + "'"); //set non cache headers _agent.prepareNonCacheResponse(hres); hres.sendRedirect(hres.encodeRedirectURL(loginUrl)); ret = Valve.END_PIPELINE; return ret; } else { if (debug >= 1) log("T8-2 SSO cookie is not present, but login optional process is not required"); } } //T8-3 if (debug >= 1) log("T8-3 SSO cookie is not present, checking for outbound relaying"); if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null)) { log("T8-3 SSO cookie not present and relaying was not requested, skipping"); //context.invokeNext(request, response); ret = Valve.INVOKE_NEXT; return ret; } } // This URI should be protected by SSO, go on ... if (debug >= 1) log("Session is: " + session); // ------------------------------------------------------------------ // Invoke the SSO Agent // ------------------------------------------------------------------ if (debug >= 1) log("Executing agent..."); _agent.setCatalinaContainer((Container) request.getContext()); //T10 /josso_security_check // ------------------------------------------------------------------ // Check if a user has been authenticated and should be checked by the agent. // ------------------------------------------------------------------ if (debug >= 1) log("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'"); if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri()) && hreq.getParameter("josso_assertion_id") != null) { if (debug >= 1) log("T10 josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '" + hreq.getParameter("josso_assertion_id")); assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER); HttpSSOAgentRequest relayRequest; relayRequest = new HttpSSOAgentRequest(SSOAgentRequest.ACTION_RELAY, null, localSession, assertionId); if (debug >= 1) log("T10 Outbound relaying requested for assertion id=" + assertionId + " sessionID=" + relayRequest.getSessionId()); relayRequest.setRequest(hreq); relayRequest.setResponse(hres); relayRequest.setContext(request.getContext()); SingleSignOnEntry entry = _agent.processRequest(relayRequest); //T10-1 if (entry == null) { // This is wrong! We should have an entry here! if (debug >= 1) log("T10-1 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!"); } //T10-2 if (debug >= 1) log("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]"); if (debug >= 1) log("T10-2 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 securityCheck(hreq, hres, entry, cfg, "T10"); /*try { cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId); hres.addCookie(cookie); } catch (Exception e) { log("Pas de bras pas de chocolat !", e); } jossoSessionId = entry.ssoId; //T10-3 //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise String requestURI = getSavedSplashResource(session.getSession()); if(requestURI == null) { requestURI = getSavedRequestURL(session); 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 (debug >= 1) log("T10-3 No saved request found, using : '" + requestURI + "'"); } } clearSavedRequestURLs(session); _agent.clearAutomaticLoginReferer(hreq); _agent.prepareNonCacheResponse(hres); //T10-4 // Check if we have a post login resource : String postAuthURI = cfg.getPostAuthenticationResource(); if (postAuthURI != null) { String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI); if (debug >= 1) log("T10-4 Redirecting to post-auth-resource '" + postAuthURL + "'"); hres.sendRedirect(postAuthURL); } else { if (debug >= 1) log("T10-4 Redirecting to original '" + requestURI + "'"); hres.sendRedirect(hres.encodeRedirectURL(requestURI)); //on garde des fois que ... theOriginal = hres.encodeRedirectURL(requestURI); } _agent.addEntrySSOIDsuccessed(entry.ssoId); log("T10 Fin josso_check jossoSessionId="+jossoSessionId);*/ //c'est pas fini et pas en erreur pourtant ... ret = Valve.END_PIPELINE; return ret; } //T11 // si on arrive la c'est une erreur! log("T11 Fin de la boucle validate donc tout va bien"); ret = Valve.INVOKE_NEXT; return ret; } catch (Throwable t) { // This is a 'hack' : Because this valve exectues before the ErrorReportingValve, we need to preapare // some stuff and invoke the next valve in the chain always ... // Store this error, it will be checked by the ErrorReportingValve hreq.setAttribute(Globals.EXCEPTION_ATTR, t); // Mark this response as error! response.setError(); // Let the next valves work on this //context.invokeNext(request, response); ret = Valve.END_PIPELINE; } finally { if (debug >= 1) log("Processed : " + hreq.getContextPath() + " [" + hreq.getRequestURL() + "] ret=" + ret); //return ret; } log("retourne ret=" + ret); return ret; }