List of usage examples for javax.servlet ServletRequest getLocalAddr
public String getLocalAddr();
From source file:de.zib.gndms.gndms.security.LocalRequestSkippingChannelProcessingFilter.java
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final String remoteAddr = req.getRemoteAddr(); logger.info("request from: " + remoteAddr); if (remoteAddr.equals(req.getLocalAddr())) chain.doFilter(req, res);//from w ww . j a va 2 s . c om else super.doFilter(req, res, chain); // overriden method implementation }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception { final Authenticator authenticator = authenticatorProvider.getAuthenticator(); final String authMethod; switch (authProps.getAuthType()) { case BASIC:/* w ww .j a va 2s.co m*/ authMethod = Constraint.__BASIC_AUTH; break; case DIGEST: authMethod = Constraint.__DIGEST_AUTH; break; default: authMethod = "customauth"; } Constraint constraint = new Constraint(); constraint.setName(authMethod); constraint.setRoles(new String[] { "user" }); constraint.setAuthenticate(true); ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() { @Override public void setConfiguration(AuthConfiguration configuration) { } @Override public String getAuthMethod() { return authMethod; } @Override public void prepareRequest(ServletRequest request) { } @Override public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr()); int remotePort = request.getRemotePort(); String localAddress = StringUtils.trimToEmpty(request.getLocalAddr()); int localPort = request.getLocalPort(); String protocol = StringUtils.trimToEmpty(request.getProtocol()); String method = StringUtils.trimToEmpty(request.getMethod()); String requestURI = StringUtils.trimToEmpty(request.getRequestURI()); Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request); Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>(); for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) { queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue())); } EntityProvider entityProvider = new EntityProvider() { @Override public byte[] getEntity() throws IOException { byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME); if (entity == null) { entity = IOUtils.toByteArray(req.getInputStream()); req.setAttribute(ATTRIBUTE_NAME, entity); } return entity; } }; RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort, protocol, method, requestURI, headers, queryParameters, entityProvider, configuration.getRequestInformation(request)); try { AuthenticationResult result = authenticator.authenticate(requestInfo); for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) { if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) { for (int i = 0; i < entry.getValue().size(); i++) { if (i == 0) { response.setHeader(entry.getKey(), entry.getValue().get(i)); } else { response.addHeader(entry.getKey(), entry.getValue().get(i)); } } } } switch (result.getStatus()) { case CHALLENGED: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_CONTINUE; case SUCCESS: Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()), null); Subject subject = new Subject(); subject.getPrincipals().add(userPrincipal); return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" })); case FAILURE: default: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_FAILURE; } } catch (Throwable t) { logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " (" + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t); eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(), "Error in HTTP authentication for " + connectorProperties.getName(), t)); throw new ServerAuthException(t); } } @Override public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } }); securityHandler.addConstraintMapping(constraintMapping); securityHandler.setHandler(handler); return securityHandler; }
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/>//from ww w . j av a2s .c om * 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(); } } }
From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java
private boolean canOpenSwingGui(final ServletRequest request) { try {//w w w. java 2s. co m return !GraphicsEnvironment.isHeadless() && InetAddress.getByName(request.getLocalAddr()).isLoopbackAddress(); } catch (UnknownHostException e) { // unexpected, but still fall back to fail-safe false return false; } }