List of usage examples for javax.servlet ServletRequest getParameter
public String getParameter(String name);
String
, or null
if the parameter does not exist. From source file:fr.paris.lutece.plugins.directory.modules.rest.service.DirectoryRestService.java
/** * {@inheritDoc}/*from w w w.j a va 2 s. c o m*/ */ @Override public Record completeRecord(int nIdRecord, ServletRequest request) throws DirectoryErrorException, DirectoryRestException { Record record = getRecord(nIdRecord, (HttpServletRequest) request); List<RecordField> listRecordFields = getRecordFields((HttpServletRequest) request, record); List<RecordField> listOldRecordField = record.getListRecordField(); // remove all non-relevant old record fields (null record fields) removeNullRecordFields(listOldRecordField); for (RecordField oldRecordField : listOldRecordField) { int nIdEntry = oldRecordField.getEntry().getIdEntry(); // idField should be 0 IF AND ONLY IF the entry is a "file". int nIdField = (oldRecordField.getField() == null) ? 0 : oldRecordField.getField().getIdField(); RecordField submitRecordField = findRecordField(nIdEntry, nIdField, listRecordFields); if (submitRecordField == null) { listRecordFields.add(oldRecordField); } else { // old value is kept and NOT modified, the new value is dropped. if (oldRecordField.getFile() != null) { // entry type file removeRecordField(nIdEntry, nIdField, listRecordFields); // get old field data oldRecordField.getFile().setPhysicalFile(PhysicalFileHome.findByPrimaryKey( oldRecordField.getFile().getPhysicalFile().getIdPhysicalFile(), getPlugin())); listRecordFields.add(oldRecordField); } if (oldRecordField.getValue() != null) { // other entries removeRecordField(nIdEntry, nIdField, listRecordFields); listRecordFields.add(oldRecordField); } } } record.setListRecordField(listRecordFields); RecordHome.updateWidthRecordField(record, getPlugin()); // do not use the workflow if update is partial String strNoWorkflowInit = request.getParameter(PARAMETER_NO_WORKFLOW); if (StringUtils.isBlank(strNoWorkflowInit) && isEntrySet(listRecordFields, record.getDirectory().getIdDirectory())) { doWorkflowActions(record, DirectoryHome.findByPrimaryKey(record.getDirectory().getIdDirectory(), getPlugin())); } return record; }
From source file:org.hi.framework.acgei.AuthenticationProcessingFilterEntryPoint.java
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = portResolver.getServerPort(request); String contextPath = req.getContextPath(); boolean inHttp = "http".equals(scheme.toLowerCase()); boolean inHttps = "https".equals(scheme.toLowerCase()); boolean includePort = true; String redirectUrl = null;/*from ww w. j av a2 s .c o m*/ boolean doForceHttps = false; Integer httpsPort = null; if (inHttp && (serverPort == 80)) { includePort = false; } else if (inHttps && (serverPort == 443)) { includePort = false; } if (forceHttps && inHttp) { httpsPort = (Integer) portMapper.lookupHttpsPort(new Integer(serverPort)); if (httpsPort != null) { doForceHttps = true; if (httpsPort.intValue() == 443) { includePort = false; } else { includePort = true; } } } if (serverSideRedirect) { if (doForceHttps) { // before doing server side redirect, we need to do client redirect to https. String servletPath = req.getServletPath(); String pathInfo = req.getPathInfo(); String query = req.getQueryString(); redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath + servletPath + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : "?" + query); } else { if (logger.isDebugEnabled()) { logger.debug("Server side forward to: " + loginFormUrl); } RequestDispatcher dispatcher = req.getRequestDispatcher(loginFormUrl); dispatcher.forward(request, response); return; } } else { if (doForceHttps) { redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath + loginFormUrl; } else { redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath + loginFormUrl; } } if (logger.isDebugEnabled()) { logger.debug("Redirecting to: " + redirectUrl); } //------------- for DWZ ------------------// if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With")) || request.getParameter("ajax") != null) { PrintWriter out = response.getWriter(); out.println("{\"statusCode\":\"301\",\"message\":\"Session Timeout! Please re-sign in!\"}"); throw new BusinessException("Session Timeout"); // throw new BusinessException("{\"statusCode\":\"301\",\"message\":\"Session Timeout! Please re-sign in!\"}"); } else { ((HttpServletResponse) response) .sendRedirect(((HttpServletResponse) response).encodeRedirectURL(redirectUrl)); } }
From source file:org.pentaho.platform.web.http.filters.PentahoWebContextFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String requestStr = httpRequest.getRequestURI(); if (requestStr != null && requestStr.endsWith(WEB_CONTEXT_JS) && httpRequest.getAttribute(FILTER_APPLIED) == null) { httpRequest.setAttribute(FILTER_APPLIED, Boolean.TRUE); // split out a fully qualified url, guaranteed to have a trailing slash IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext(); String contextPath = requestContext.getContextPath(); try {//from ww w.j av a 2 s.c o m response.setContentType("text/javascript"); //$NON-NLS-1$ OutputStream out = response.getOutputStream(); out.write(initialCommentBytes); byte[] contextPathBytes = THREAD_LOCAL_CONTEXT_PATH.get(); byte[] requireScriptBytes = THREAD_LOCAL_REQUIRE_SCRIPT.get(); if (contextPathBytes == null) { String webContext = "var CONTEXT_PATH = '" + contextPath + "';\n\n"; //$NON-NLS-1$ //$NON-NLS-2$ contextPathBytes = webContext.getBytes(); THREAD_LOCAL_CONTEXT_PATH.set(contextPathBytes); if (requireScriptBytes == null) { String requireJsLocation = "content/common-ui/resources/web/require.js"; String requireJsConfigLocation = "content/common-ui/resources/web/require-cfg.js"; String requireScript = "document.write(\"<script type='text/javascript' src='" + contextPath + requireJsLocation + "'></scr\"+\"ipt>\");\n" + "document.write(\"<script type=\'text/javascript\' src='" + contextPath + requireJsConfigLocation + "'></scr\"+\"ipt>\");\n"; requireScriptBytes = requireScript.getBytes(); THREAD_LOCAL_REQUIRE_SCRIPT.set(requireScriptBytes); } } String basicAuthFlag = (String) httpRequest.getSession().getAttribute("BasicAuth"); if (basicAuthFlag != null && basicAuthFlag.equals("true")) { out.write(("document.write(\"<script type='text/javascript' src='" + contextPath + "js/postAuth.js'></scr\"+\"ipt>\");\n").getBytes("UTF-8")); } out.write(contextPathBytes); out.write(fullyQualifiedUrl.getBytes()); out.write(serverProtocol.getBytes()); // Compute the effective locale and set it in the global scope. Also provide it as a module if the RequireJs // system is available. Locale effectiveLocale = LocaleHelper.getLocale(); if (!StringUtils.isEmpty(request.getParameter("locale"))) { effectiveLocale = new Locale(request.getParameter("locale")); } // setup the RequireJS config object for plugins to extend out.write(REQUIRE_JS_CFG_START); // Let all plugins contribute to the RequireJS config printResourcesForContext(REQUIRE_JS, out, httpRequest, false); out.write(requireScriptBytes); printSessionName(out); printLocale(effectiveLocale, out); printHomeFolder(out); printReservedChars(out); printReservedCharsDisplay(out); printReservedRegexPattern(out); boolean requireJsOnly = "true".equals(request.getParameter("requireJsOnly")); if (!requireJsOnly) { // print global resources defined in plugins printResourcesForContext(GLOBAL, out, httpRequest, false); // print out external-resources defined in plugins if a context has been passed in String contextName = request.getParameter(CONTEXT); boolean cssOnly = "true".equals(request.getParameter("cssOnly")); if (StringUtils.isNotEmpty(contextName)) { printResourcesForContext(contextName, out, httpRequest, cssOnly); } } // Any subclass can add more information to webcontext.js addCustomInfo(out); out.close(); return; } finally { httpRequest.removeAttribute(FILTER_APPLIED); } } else { chain.doFilter(httpRequest, httpResponse); return; } }
From source file:org.lockss.servlet.LockssOiosamlSpFilter.java
/** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an <AuthnRequest> is sent * to the Login Site./*from www . ja v a 2 s. com*/ * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final String DEBUG_HEADER = "doFilter(): "; if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Starting..."); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { if (log.isDebug3()) log.debug3(DEBUG_HEADER + "isFilterInitialized() = false"); try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); if (log.isDebug2()) { log.debug2(DEBUG_HEADER + "Forwarded to /saml/configure."); log.debug2(DEBUG_HEADER + "Done."); } return; } } else { if (log.isDebug3()) log.debug3(DEBUG_HEADER + "isFilterInitialized() = true"); } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warning("Running in developer mode, skipped regular filter."); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } if (cleanerRunning.compareAndSet(false, true)) { int maxInactiveInterval = ((HttpServletRequest) request).getSession().getMaxInactiveInterval(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "maxInactiveInterval = " + maxInactiveInterval); if (maxInactiveInterval < 0) { maxInactiveInterval = 3600; } SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), maxInactiveInterval, 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath() .equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { if (log.isDebug()) log.debug(DEBUG_HEADER + "Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebug()) log.debug(DEBUG_HEADER + "session.getId() = " + session.getId()); Boolean forceAuthn = false; if (request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "forceAuthnAsString = " + forceAuthnAsString); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } if (log.isDebug3()) log.debug3(DEBUG_HEADER + "forceAuthn = " + forceAuthn); // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "actualAssuranceLevel = " + actualAssuranceLevel); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "assuranceLevel = " + assuranceLevel); if (actualAssuranceLevel > 0 && actualAssuranceLevel < assuranceLevel) { sessionHandler.logOut(session); log.warning("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException( "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebug()) { log.debug(DEBUG_HEADER + "Everything is OK."); log.debug(DEBUG_HEADER + "Subject: " + ua.getSubject()); log.debug(DEBUG_HEADER + "NameID Format: " + ua.getNameIDFormat()); log.debug(DEBUG_HEADER + "Common Name: " + ua.getCommonName()); log.debug(DEBUG_HEADER + "UserId: " + ua.getUserId()); log.debug(DEBUG_HEADER + "Authenticated?: " + ua.isAuthenticated()); log.debug(DEBUG_HEADER + "Signed?: " + ua.isSigned()); } Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); }
From source file:com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java
public void process(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; HttpServletRequest servletRequest = (HttpServletRequest) request; String token = ""; String clientVersion = ""; String deviceType = ""; //header??/* ww w . j a va 2 s .co m*/ String base64Str = servletRequest.getHeader("clientHeader"); if (!StringUtils.isEmpty(base64Str)) { String headerJsonStr = Base64Utils.getFromBase64(base64Str); JSONObject headerJson = JSONObject.parseObject(headerJsonStr); token = headerJson.getString("accessToken"); try { clientVersion = headerJson.getString("apiClientVersion"); deviceType = headerJson.getString("deviceType"); //add by xuhui 20170406 if (!StringUtils.isEmpty(clientVersion)) { if ("iOS".equals(deviceType) && iosAppVertion.compareTo(clientVersion) > 0) { JSONObject jSONObject = new JSONObject(); PrintWriter pw = httpServletResponse.getWriter(); jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.FORCEUPDATE.getCode()); jSONObject.put("success", true); jSONObject.put("code", 201); Map<String, Object> map = new HashMap(); //? map.put("updateUrl", ""); map.put("updateInfo", ""); map.put("updateTargetVersion", iosAppVertion); map.put("forceUpdate", true); map.put("appType", "iOS"); jSONObject.put("data", map); pw.write(jSONObject.toJSONString()); pw.flush(); } if ("android".equals(deviceType) && andriodAppVersion.compareTo(clientVersion) > 0) { JSONObject jSONObject = new JSONObject(); PrintWriter pw = httpServletResponse.getWriter(); jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.FORCEUPDATE.getCode()); jSONObject.put("success", true); jSONObject.put("code", 201); Map<String, Object> map = new HashMap(); //? map.put("updateUrl", "http://10.154.40.42:7777/lrh_apk_android_20_v0.0.1/vcredit_lrh_debug_v0.0.2_2017_0421_1041_Vcredit_TecentQQ.apk"); map.put("updateInfo", ""); map.put("updateTargetVersion", andriodAppVersion); map.put("forceUpdate", true); map.put("appType", "android"); jSONObject.put("data", map); pw.write(jSONObject.toJSONString()); pw.flush(); } } } catch (Exception e) { } } // String token = request.getParameter("accessToken") == null ? accessTokenFromHeader : request.getParameter("accessToken"); if (StringUtils.isEmpty(token)) { token = servletRequest.getSession().getId().toUpperCase(); } String openId = request.getParameter("open_id"); httpServletResponse.setHeader("Content-Type", "application/json"); try { if (servletRequest.getServletPath().equals(securityProperties.getLoginSecurityUrl())) { chain.doFilter(request, response); } else if (servletRequest.getServletPath().equals("/favicon.ico")) { chain.doFilter(request, response); // PrintWriter pw = httpServletResponse.getWriter(); // pw.write("favicon.ico"); // pw.flush(); } else if (openId == null && null == token) { unauthorizedRequest(httpServletResponse); } else if (needAuthentication(servletRequest.getServletPath())) { // JSONObject currentUser = securityService.getUserByAccessToken(token); JSONObject currentUser = redisTemplate.get(RedisCacheKeys.ACCOUNT_CACHE_TOKEN + token, JSONObject.class); if (null == currentUser) { unauthorizedRequest(httpServletResponse); } else { chain.doFilter(request, response); } } else { chain.doFilter(request, response); } } catch (ServletException ex) { logger.error(ex.getMessage(), ex); serverErrorRequest(httpServletResponse); } }
From source file:org.alfresco.repo.webdav.auth.HTTPRequestAuthenticationFilter.java
/** * Run the authentication filter/* w ww .j a v a 2 s .c om*/ * * @param req * ServletRequest * @param resp * ServletResponse * @param chain * FilterChain * @exception ServletException * @exception IOException */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // Assume it's an HTTP request final HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the user details object from the session SessionUser user = (SessionUser) httpReq.getSession().getAttribute(AUTHENTICATION_USER); if (user == null) { // Check for the auth header String authHdr = httpReq.getHeader(httpServletRequestAuthHeaderName); if (logger.isDebugEnabled()) { if (authHdr == null) { logger.debug("Header not found: " + httpServletRequestAuthHeaderName); } else { logger.debug("Header is <" + authHdr + ">"); } } // Throw an error if we have an unknown authentication if ((authHdr != null) && (authHdr.length() > 0)) { // Get the user final String userName; if (m_authPattern != null) { Matcher matcher = m_authPattern.matcher(authHdr); if (matcher.matches()) { userName = matcher.group(); if ((userName == null) || (userName.length() < 1)) { if (logger.isDebugEnabled()) { logger.debug("Extracted null or empty user name from pattern " + m_authPatternString + " against " + authHdr); } reject(httpReq, httpResp); return; } } else { if (logger.isDebugEnabled()) { logger.debug("no pattern match for " + m_authPatternString + " against " + authHdr); } reject(httpReq, httpResp); return; } } else { userName = authHdr; } if (logger.isDebugEnabled()) { logger.debug("User = " + userName); } // Get the authorization header user = transactionService.getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<SessionUser>() { public SessionUser execute() throws Throwable { try { // Authenticate the user m_authComponent.clearCurrentSecurityContext(); m_authComponent.setCurrentUser(userName); return createUserEnvironment(httpReq.getSession(), userName, authenticationService.getCurrentTicket(), true); } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed", ex); } return null; // Perhaps auto-creation/import is disabled } } }); } else { // Check if the request includes an authentication ticket String ticket = req.getParameter(ARG_TICKET); if (ticket != null && ticket.length() > 0) { // Debug if (logger.isDebugEnabled()) logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket); try { // Validate the ticket authenticationService.validate(ticket); // Need to create the User instance if not already available user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), ticket, true); } catch (AuthenticationException authErr) { // Clear the user object to signal authentication failure if (logger.isDebugEnabled()) { logger.debug("Failed", authErr); } user = null; } } } // Check if the user is authenticated, if not then prompt again if (user == null) { // No user/ticket, force the client to prompt for logon details reject(httpReq, httpResp); return; } } // Chain other filters chain.doFilter(req, resp); }
From source file:org.alfresco.repo.webdav.auth.AuthenticationFilter.java
/** * Run the authentication filter/* w w w . j a va 2 s . c om*/ * * @param context ServletContext * @param req ServletRequest * @param resp ServletResponse * @param chain FilterChain * @exception ServletException * @exception IOException */ public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) logger.debug("Entering AuthenticationFilter."); // Assume it's an HTTP request HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the user details object from the session SessionUser user = getSessionUser(context, httpReq, httpResp, false); if (user == null) { if (logger.isDebugEnabled()) logger.debug("There is no user in the session."); // Get the authorization header String authHdr = httpReq.getHeader("Authorization"); if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) { if (logger.isDebugEnabled()) logger.debug("Basic authentication details present in the header."); byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes()); // ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2); for (String encoding : ENCODINGS) { CharsetDecoder decoder = Charset.forName(encoding).newDecoder() .onMalformedInput(CodingErrorAction.REPORT); try { // Attempt to decode using this charset String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString(); // It decoded OK but we may already have tried this string. if (!attemptedAuths.add(basicAuth)) { // Already tried - no need to try again continue; } String username = null; String password = null; // Split the username and password int pos = basicAuth.indexOf(":"); if (pos != -1) { username = basicAuth.substring(0, pos); password = basicAuth.substring(pos + 1); } else { username = basicAuth; password = ""; } // Go to the repo and authenticate Authorization auth = new Authorization(username, password); if (auth.isTicket()) { authenticationService.validate(auth.getTicket()); } else { authenticationService.authenticate(username, password.toCharArray()); authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password)); } user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), authenticationService.getCurrentTicket(), false); // Success so break out break; } catch (CharacterCodingException e) { if (logger.isDebugEnabled()) logger.debug("Didn't decode using " + decoder.getClass().getName(), e); } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) logger.debug("Authentication error ", ex); } catch (NoSuchPersonException e) { if (logger.isDebugEnabled()) logger.debug("There is no such person error ", e); } } } else { // Check if the request includes an authentication ticket String ticket = req.getParameter(ARG_TICKET); if (ticket != null && ticket.length() > 0) { // PowerPoint bug fix if (ticket.endsWith(PPT_EXTN)) { ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length()); } // Debug if (logger.isDebugEnabled()) logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket); // Validate the ticket authenticationService.validate(ticket); authenticationListener.userAuthenticated(new TicketCredentials(ticket)); // Need to create the User instance if not already available String currentUsername = authenticationService.getCurrentUserName(); user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false); } } // Check if the user is authenticated, if not then prompt again if (user == null) { if (logger.isDebugEnabled()) logger.debug("No user/ticket, force the client to prompt for logon details."); httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\""); httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResp.flushBuffer(); return; } } else { authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket())); } // Chain other filters chain.doFilter(req, resp); }
From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java
/** * This filter is basically what secures Infoglue and enforces the authentication framework. *///from w ww .j a v a2 s. c om public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws ServletException, IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { if (CmsPropertyHandler.getServletContext() == null) { CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath()); } String URI = httpServletRequest.getRequestURI(); String URL = httpServletRequest.getRequestURL().toString(); if (logger.isInfoEnabled()) { logger.info("URI: + " + URI); logger.info("URL: + " + URL); } String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8"); if (URI == null) logger.error("URI was null - requestURI:" + requestURI); if (URL == null) logger.error("URL was null - requestURI:" + requestURI); if (requestURI == null) logger.error("requestURI was null"); if (loginUrl == null) { logger.error("loginUrl was null - fix this."); loginUrl = "Login.action"; } if (invalidLoginUrl == null) { logger.error("invalidLoginUrl was null - fix this."); invalidLoginUrl = "Login!invalidLogin.action"; } if (logoutUrl == null) { logger.error("logoutUrl was null - fix this."); logoutUrl = "ExtranetLogin!logout.action"; } if (uriMatcher == null) { logger.error("uriMatcher was null - fix this."); String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER); uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false); } if (!CmsPropertyHandler.getIsValidSetup() && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) { httpServletResponse.sendRedirect("Install!input.action"); return; } //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally. if (URI != null && URL != null && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1 || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1 || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1 || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1 || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1 || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1 || uriMatcher.matches(requestURI))) { fc.doFilter(request, response); return; } // make sure we've got an HTTP request if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) throw new ServletException("InfoGlue Filter protects only HTTP resources"); HttpSession session = ((HttpServletRequest) request).getSession(); String sessionTimeout = CmsPropertyHandler.getSessionTimeout(); try { Integer.parseInt(sessionTimeout); } catch (Exception e) { sessionTimeout = "1800"; } if (sessionTimeout == null) sessionTimeout = "1800"; session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue()); // if our attribute's already present, don't do anything //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER)); if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) { //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER)); //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) //{ // checkSuccessRedirect(request, response, URL); //} //else //{ fc.doFilter(request, response); return; //} } // otherwise, we need to authenticate somehow boolean isAdministrator = false; String userName = request.getParameter("j_username"); String password = request.getParameter("j_password"); if (userName != null && password != null) { String administratorUserName = CmsPropertyHandler.getAdministratorUserName(); boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password); isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true : false; } //First we check if the user is logged in to the container context if (!isAdministrator) { logger.info("Principal:" + httpServletRequest.getUserPrincipal()); if (httpServletRequest.getUserPrincipal() != null && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) { userName = httpServletRequest.getUserPrincipal().getName(); logger.info("Now trusting the container logged in identity..."); } } String authenticatedUserName = userName; if (!isAdministrator) { String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid"); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) { byte[] bytes = Base64.decodeBase64(encodedUserNameCookie); encodedUserNameCookie = new String(bytes, "utf-8"); //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "="); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); String servletContextUserName = (String) filterConfig.getServletContext() .getAttribute(encodedUserNameCookie); logger.info("servletContextUserName:" + servletContextUserName); if (servletContextUserName != null && !servletContextUserName.equals("")) { authenticatedUserName = servletContextUserName; } else { Cookie cookie_iguserid = new Cookie("iguserid", "none"); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(0); httpServletResponse.addCookie(cookie_iguserid); Cookie cookie_igpassword = new Cookie("igpassword", "none"); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(0); httpServletResponse.addCookie(cookie_igpassword); authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } else { authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } logger.info("authenticatedUserName:" + authenticatedUserName); if (authenticatedUserName != null) { logger.info("Getting the principal from user name:" + authenticatedUserName); InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName); if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) { //throw new Exception("This user is not authorized to log in..."); httpServletResponse.sendRedirect("unauthorizedLogin.jsp"); NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:", "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); return; } //TODO - we must fix so these caches are individual to the person - now a login will slow down for all //CacheController.clearCache("authorizationCache"); //CacheController.clearCache("personalAuthorizationCache", user.getName()); CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName()); // Store the authenticated user in the session if (session != null) { session.setAttribute(INFOGLUE_FILTER_USER, user); setUserProperties(session, user); } //TEST - transferring auth to deliverworking try { if (userName != null && password != null) { DesEncryptionHelper encHelper = new DesEncryptionHelper(); String encryptedName = encHelper.encrypt(userName); String encryptedPassword = encHelper.encrypt(password); String encryptedNameAsBase64 = Base64 .encodeBase64URLSafeString(encryptedName.getBytes("utf-8")); String encryptedPasswordAsBase64 = Base64 .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8")); String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl(); String[] parts = deliverBaseUrl.split("/"); deliverBaseUrl = "/" + parts[parts.length - 1]; //logger.info("used cmsBaseUrl:" + cmsBaseUrl); ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl); if (servletContext == null) { logger.error("Could not autologin to " + deliverBaseUrl + ". Set cross context = true in Tomcat config."); } else { logger.info("Added encryptedName:" + encryptedName + " = " + user.getName() + " to deliver context"); servletContext.setAttribute(encryptedName, user.getName()); } int cmsCookieTimeout = 1800; //30 minutes default String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout(); if (cmsCookieTimeoutString != null) { try { cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim()); } catch (Exception e) { } } //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ")); Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_iguserid); //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ")); Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_igpassword); //logger.info(encryptedName + "=" + userName); //logger.info("After attribute:" + servletContext.getAttribute(encryptedName)); } } catch (Exception e) { logger.error("Error: " + e.getMessage(), e); } //END TEST String logUserName = userName; if (logUserName == null || logUserName.equals("") && user != null) logUserName = user.getName(); if (logUserName == null || logUserName.equals("")) logUserName = authenticatedUserName; if (logUserName == null || logUserName.equals("")) logUserName = "Unknown"; NotificationMessage notificationMessage = new NotificationMessage("Login success:", "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) { checkSuccessRedirect(request, response, URL); } else { fc.doFilter(request, response); return; } } else { if (userName != null && !userName.equals("")) { NotificationMessage notificationMessage = new NotificationMessage("Login failed:", "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName, "name"); TransactionHistoryController.getController().create(notificationMessage); } } } catch (Exception e) { logger.error("Error authenticating user:" + e.getMessage(), e); httpServletRequest.setAttribute("error", new Exception( "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account.")); httpServletResponse.sendError(500); return; } }
From source file:org.openmrs.module.personalhr.web.filter.PhrSecurityFilter.java
/** * For an authenticated user to access a non-excluded URL: * 1. check if a redirect is needed first; * 2. if a redirect is not needed, check PHR URL level security * <p/>// w w w .jav a 2 s . c o m * PHR URL redirecting rules: * 1. Check user type: unauthenticated user, PHR user, non-PHR user * 2. Unauthenticated user: no-redirect * 3. PHR user: 1) redirect /openmrs/index.htm and /openmrs/phr to corresponding PHR pages; 2) re-append missing patientId or personId parameters * 4. non-PHR user: redirected to non-PHR pages by PHR login servlet * <p/> * PHR URL level security checking rules: * 1. Check user type: unauthenticated user, PHR user, non-PHR user * 2. Unauthenticated user: skip * 3. PHR user: check against PHR allowed url list and corresponding privilege required * 4. non-PHR user: block access to /phr/ domain * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { HttpServletRequest hsr = (HttpServletRequest) request; final String requestURI = hsr.getRequestURI(); final String patientId = hsr.getParameter("patientId"); final String personId = hsr.getParameter("personId"); final String encounterId = hsr.getParameter("encounterId"); String phrRole = null; this.log.warn("Entering PhrSecurityFilter.doFilter: " + requestURI + "|" + patientId + "|" + personId + "|" + encounterId); //redirect /phr/ to /phr/index.htm if (requestURI.toLowerCase().endsWith("/phr/") || requestURI.toLowerCase().endsWith("/phr")) { String redirect = "/phr/index.htm"; ((HttpServletResponse) response).sendRedirect(hsr.getContextPath() + redirect); return; } //This filter applies to authenticated users only if (Context.isAuthenticated()) { final User user = Context.getAuthenticatedUser(); phrRole = getPhrService().getPhrRole(user); //Check if the URL is in the excluded (for checking) list if (shouldCheckAccessToUrl(requestURI)) { try { PersonalhrUtil.addMinimumTemporaryPrivileges(); final Integer patId = PersonalhrUtil.getParamAsInteger(patientId); Patient pat = patId == null ? null : Context.getPatientService().getPatient(patId); final Integer perId = PersonalhrUtil.getParamAsInteger(personId); final Person per = perId == null ? null : Context.getPersonService().getPerson(perId); final Integer encId = PersonalhrUtil.getParamAsInteger(encounterId); final Encounter enc = encId == null ? null : Context.getEncounterService().getEncounter(encId); if (enc != null) { pat = enc.getPatient(); } //************************** //Perform redirect checking //************************** if (phrRole != null) { //1) redirect /openmrs/index.htm if ((requestURI.toLowerCase().contains("index.htm") || requestURI.toLowerCase().endsWith("/openmrs/") || requestURI.toLowerCase().endsWith("/openmrs")) && !requestURI.toLowerCase().contains("/phr/")) { String redirect = requestURI; if (phrRole != null) { final Integer userPersonId = (user == null ? null : user.getPerson().getId()); if (PhrBasicRole.PHR_PATIENT.getValue().equals(phrRole)) { if (userPersonId != null) { redirect = "/phr/patientDashboard.form?patientId=" + userPersonId; } else { this.log.error("Error: PHR Patient's person id is null!"); } //PersonalhrUtil.addTemporayPrivileges(); } else if (PhrBasicRole.PHR_RESTRICTED_USER.getValue().equals(phrRole)) { if (userPersonId != null) { redirect = "/phr/restrictedUserDashboard.form?personId=" + userPersonId; } else { this.log.error("Error: PHR Restricted user's person id is null!"); } //PersonalhrUtil.addTemporayPrivileges(); } else if (PhrBasicRole.PHR_ADMINISTRATOR.getValue().equals(phrRole)) { redirect = "/phr/findPatient.htm"; //PersonalhrUtil.addTemporayPrivileges(); } this.log.debug("***URL access is redirected to " + redirect + " for user " + user + "|" + requestURI + "|" + pat + "|" + per); getPhrService().logEvent(PhrLogEvent.ACCESS_REDIRECT, new Date(), user, ((HttpServletRequest) request).getSession().getId(), pat, "redirect=" + redirect + "; client_ip=" + request.getLocalAddr()); ((HttpServletResponse) response) .sendRedirect(((HttpServletRequest) request).getContextPath() + redirect); return; } } else if ((requestURI.contains("patientDashboard.form") && patId == null) || (requestURI.contains("restrictedUserDashboard.form") && perId == null)) { //2) re-append missing patientId or personId parameters String redirect = requestURI; if (phrRole != null) { final Integer userPersonId = (user == null ? null : user.getPerson().getId()); if (PhrBasicRole.PHR_PATIENT.getValue().equals(phrRole)) { if (userPersonId != null) { redirect = "/phr/patientDashboard.form?patientId=" + userPersonId; } else { this.log.error("Error: PHR Patient's person id is null!"); } //PersonalhrUtil.addTemporayPrivileges(); } else if (PhrBasicRole.PHR_RESTRICTED_USER.getValue().equals(phrRole)) { if (userPersonId != null) { redirect = "/phr/restrictedUserDashboard.form?personId=" + userPersonId; } else { this.log.error("Error: PHR Restricted user's person id is null!"); } //PersonalhrUtil.addTemporayPrivileges(); } this.log.debug("***URL access is redirected to " + redirect + " for user " + user + "|" + requestURI + "|" + pat + "|" + per); ((HttpServletResponse) response) .sendRedirect(((HttpServletRequest) request).getContextPath() + redirect); return; } } } //************************** //Perform security checking //************************** if (phrRole != null) { if (!requestURI.toLowerCase().contains("/phr/") && !requestURI.toLowerCase().contains("/personalhr/") && !getPhrService() .isUrlAllowed(requestURI, pat, per, Context.getAuthenticatedUser())) { this.log.debug("***URL access not allowed for this PHR user!!! " + requestURI + "|" + pat + "|" + per + "|" + user); getPhrService().logEvent(PhrLogEvent.ACCESS_NOT_ALLOWED, new Date(), user, ((HttpServletRequest) request).getSession().getId(), pat, "requestURI=" + requestURI + "; client_ip=" + request.getLocalAddr()); this.config.getServletContext().getRequestDispatcher(this.loginForm).forward(request, response); return; } else { this.log.debug("***URL access allowed for this PHR user!!! " + user + "|" + requestURI + "|" + pat + "|" + per); } } else { if (!(requestURI.toLowerCase().contains("/admin/")) && ((requestURI.toLowerCase().contains("/phr/") || requestURI.toLowerCase().contains("/personalhr/")))) { this.log.debug("***URL access not allowed for this non-PHR user!!! " + user + "|" + requestURI + "|" + pat + "|" + per); if (this.config == null) { log.error("config is null"); return; } if (this.config.getServletContext() == null) { log.error("servletContext is null"); return; } if (this.config.getServletContext().getRequestDispatcher(this.loginForm) == null) { log.error("requestDispatcher is null"); return; } this.config.getServletContext().getRequestDispatcher(this.loginForm).forward(request, response); return; } else { this.log.debug("***URL access allowed for this non-PHR user!!! " + user + "|" + requestURI + "|" + pat + "|" + per); } } //**************************************************** //Perform event logging for "POST" type request only //**************************************************** if (enableEventLogging && "POST".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) { String command = request.getParameter("command"); if (command != null) { getPhrService().logEvent(PhrLogEvent.SUBMIT_CHANGES, new Date(), user, ((HttpServletRequest) request).getSession().getId(), pat, "requestURI=" + requestURI + "; command=" + command + "; client_ip=" + request.getLocalAddr()); } else if (!(requestURI.toLowerCase().contains("/admin") || requestURI.toLowerCase().contains("get") || requestURI.toLowerCase().contains("find") || requestURI.toLowerCase().contains("list") || requestURI.toLowerCase().contains("check") || requestURI.toLowerCase().contains("validate"))) { getPhrService().logEvent(PhrLogEvent.SUBMIT_CHANGES, new Date(), user, ((HttpServletRequest) request).getSession().getId(), pat, "requestURI=" + requestURI + "; client_ip=" + request.getLocalAddr()); } } } finally { PersonalhrUtil.removeMinimumTemporaryPrivileges(); } } else { this.log.debug("***URL access is unchecked and allowed for this authenticated user!!! " + user + "|" + requestURI + "|" + patientId + "|" + personId + "|" + encounterId); } } else { this.log.debug("***URL access is allowed for all unauthenticated users!!! " + requestURI + "|" + patientId + "|" + personId + "|" + encounterId); } try { //Add temporary privilege if (phrRole != null) { PersonalhrUtil.addTemporaryPrivileges(); } chain.doFilter(request, response); } finally { if (phrRole != null) { PersonalhrUtil.removeTemporaryPrivileges(); } } }