Example usage for javax.servlet ServletRequest getRemoteAddr

List of usage examples for javax.servlet ServletRequest getRemoteAddr

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getRemoteAddr.

Prototype

public String getRemoteAddr();

Source Link

Document

Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Usage

From source file:net.big_oh.common.web.filters.ipaddress.IPAddressFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {

        HttpServletResponse resp = (HttpServletResponse) response;

        // check white list rules
        for (IPAddressWhiteListFilterRule whiteListRule : whiteListRules) {
            if (whiteListRule.doesRequestingAddressMatchRule(InetAddress.getByName(request.getRemoteAddr()))) {
                logger.info("Request from " + request.getRemoteAddr()
                        + " permitted because of matching white list rule (" + whiteListRule.toString() + ").");
                chain.doFilter(request, response);
                return;
            }//from   w w  w  .ja va  2s  . c  o m
        }

        // check blacklist rules
        for (IPAddressBlackListFilterRule blackListRule : blackListRules) {
            if (blackListRule.doesRequestingAddressMatchRule(InetAddress.getByName(request.getRemoteAddr()))) {
                logger.info("Request from " + request.getRemoteAddr()
                        + " rejected because of matching black list rule (" + blackListRule.toString() + ").");
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        logger.info(
                "Request from " + request.getRemoteAddr() + " permitted because no matching rules were found.");
        chain.doFilter(request, response);
        return;

    } else {
        logger.info("Encountered a non-HTTP request.  Processing normally.");
        chain.doFilter(request, response);
        return;
    }

}

From source file:mitm.djigzo.web.utils.IPFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse expected.");
    }/*from   w  w  w  . java  2s  . c o  m*/

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String servletPath = null;

    if (request instanceof HttpServletRequest) {
        servletPath = ((HttpServletRequest) request).getServletPath();
    }

    String remoteAddress = request.getRemoteAddr();

    if (filter.isAccepted(remoteAddress) || isServletPathExcluded(servletPath)) {
        chain.doFilter(request, response);
    } else {
        logger.warn("Request from " + remoteAddress + " to " + request.toString() + " is blocked.");

        httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Access denied (" + remoteAddress + " is not allowed to connect)");
    }
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {/*from w  ww .  j av  a  2 s  .  com*/

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:org.apache.unomi.web.ContextServlet.java

private int handleRequest(ContextRequest contextRequest, Profile profile, Session session, ContextResponse data,
        ServletRequest request, ServletResponse response, Date timestamp) throws IOException {
    List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId());

    String thirdPartyId = eventService.authenticateThirdPartyServer(
            ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr());

    int changes = EventService.NO_CHANGE;
    // execute provided events if any
    if (contextRequest.getEvents() != null && !(profile instanceof Persona)) {
        for (Event event : contextRequest.getEvents()) {
            if (event.getEventType() != null) {
                Event eventToSend = new Event(event.getEventType(), session, profile,
                        contextRequest.getSource().getScope(), event.getSource(), event.getTarget(),
                        event.getProperties(), timestamp);
                if (!eventService.isEventAllowed(event, thirdPartyId)) {
                    logger.debug("Event is not allowed : {}", event.getEventType());
                    continue;
                }//from  ww  w  .  ja v  a  2  s  . c  om
                if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) {
                    logger.debug("Profile is filtering event type {}", event.getEventType());
                    continue;
                }

                event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
                event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
                logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId()
                        + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                        + timestamp);
                changes |= eventService.send(eventToSend);
            }
        }
    }

    if (contextRequest.isRequireSegments()) {
        data.setProfileSegments(profile.getSegments());
    }

    if (contextRequest.getRequiredProfileProperties() != null) {
        Map<String, Object> profileProperties = new HashMap<String, Object>(profile.getProperties());
        if (!contextRequest.getRequiredProfileProperties().contains("*")) {
            profileProperties.keySet().retainAll(contextRequest.getRequiredProfileProperties());
        }
        data.setProfileProperties(profileProperties);
    }
    if (session != null) {
        data.setSessionId(session.getItemId());
        if (contextRequest.getRequiredSessionProperties() != null) {
            Map<String, Object> sessionProperties = new HashMap<String, Object>(session.getProperties());
            if (!contextRequest.getRequiredSessionProperties().contains("*")) {
                sessionProperties.keySet().retainAll(contextRequest.getRequiredSessionProperties());
            }
            data.setSessionProperties(sessionProperties);
        }
    }

    processOverrides(contextRequest, profile, session);

    List<ContextRequest.FilteredContent> filterNodes = contextRequest.getFilters();
    if (filterNodes != null) {
        data.setFilteringResults(new HashMap<String, Boolean>());
        for (ContextRequest.FilteredContent filteredContent : filterNodes) {
            boolean result = true;
            for (ContextRequest.Filter filter : filteredContent.getFilters()) {
                Condition condition = filter.getCondition();
                result &= profileService.matchCondition(condition, profile, session);
            }
            data.getFilteringResults().put(filteredContent.getFilterid(), result);
        }
    }

    if (!(profile instanceof Persona)) {
        data.setTrackedConditions(rulesService.getTrackedConditions(contextRequest.getSource()));
    } else {
        data.setTrackedConditions(Collections.<Condition>emptySet());
    }

    return changes;
}

From source file:org.apereo.portal.web.ExceptionLoggingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {/* ww  w . ja  v a  2 s .  c  o  m*/
        chain.doFilter(request, response);
    } catch (Throwable t) {
        StringBuilder msg = new StringBuilder();
        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            msg.append("for URL=" + req.getRequestURI());
            if (StringUtils.isNotBlank(req.getQueryString())) {
                msg.append("?" + req.getQueryString());
            }
            msg.append(", user=" + req.getRemoteUser());
            msg.append(" ");
        }
        msg.append(", from IP=" + request.getRemoteAddr());
        this.logger.error("uPortal: unhandled exception '" + t.getMessage() + "' " + msg.toString(), t);

        if (t instanceof Error) {
            throw (Error) t;
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new ServletException(t);
    }
}

From source file:org.glite.slcs.filter.AttributesAuthorizationFilter.java

/**
 * Checks if the user Shibboleth attributes grant him access.
 *///from  w  w w  .j a  v  a2  s .  c o  m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean authorized = true;
    List userAttributes = null;
    if (request instanceof HttpServletRequest) {
        authorized = false;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        LOG.info("check authorization: " + httpRequest.getRequestURI());
        // get shib user attributes
        userAttributes = attributeDefinitions_.getUserAttributes(httpRequest);
        // check if user is authorized
        authorized = accessControlList_.isAuthorized(userAttributes);

    }
    if (!authorized) {
        String remoteAddress = request.getRemoteAddr();
        LOG.error(HttpServletResponse.SC_UNAUTHORIZED + ": User (IP:" + remoteAddress + ") is not authorized: "
                + userAttributes);
        // TODO: custom 401 error page
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Based on your Shibboleth attributes, you are not authorized to access this service");
    } else {
        // user is authorized or not a HttpServletRequest, continue
        chain.doFilter(request, response);
    }
}

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:/*  ww  w .java2s.  c om*/
        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.rhq.helpers.rtfilter.filter.RtFilter.java

private void writeLogEntry(ServletRequest req, RtFilterResponseWrapper responseWrapper, String uri, String url,
        long t1) throws Exception {
    long duration = this.t2 - t1;
    if (duration < 0) {
        log.error("Calculated response time for request to [" + url + "] (" + duration + " ms) is negative!");
        return;//from  w  w  w  . ja  v a 2  s.c  o m
    }
    if (duration == 0) {
        // Impossible - we must be on Windows, where the system clock is only accurate to about 15 ms
        // (see http://www.simongbrown.com/blog/2007/08/20/millisecond_accuracy_in_java.html).
        // NOTE: With some tweaking, it is possible to make the Windows clock accurate to millisecond precision
        // (see http://www.lochan.org/2005/keith-cl/useful/win32time.html).
        // TODO: We should explain the above in our docs.
        // Bump the duration up to 1, so at least we're not saying the request defied the laws of physics.
        duration = 1;
    }

    if (log.isDebugEnabled()) {
        log.debug("Request to [" + url + "] took " + duration + " ms");
    }

    String remoteIp = req.getRemoteAddr();

    // Format: <url> <when> <duration> <status> <IP>
    StringBuilder buf = new StringBuilder();
    buf.append((this.chopUrl) ? uri : url).append(" ").append(this.t2).append(" ").append(duration).append(" ")
            .append(responseWrapper.getStatus()).append(" ").append(remoteIp);

    // Check if log file was externally truncated before writing to it. NOTE: It's important to do this just prior
    // to writing to the file to minimize the chances of the file becoming corrupt (i.e. front-padded with NUL
    // characters).
    rewindLogFileIfSizeDecreased();
    this.writer.append(buf);
    this.writer.newLine();
    if (this.flushingNeeded || ((this.requestCount % this.flushAfterLines) == 0)) {
        this.writer.flush();
        this.flushingNeeded = false;
        this.lastLogFileSize = this.logFile.length();
    }
}

From source file:de.jaxenter.eesummit.caroline.gui.filter.LogFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    String remoteAddress = null;//  w  w  w . ja  v a2s .c  o m
    String sessionId = null;
    String uid = "0";

    long start = 0;
    String url = "";
    String method = "";
    Throwable throwable = null;
    boolean dropped = false;
    String agent = null;
    try {
        Validate.isTrue(request instanceof HttpServletRequest, "filter oops?");
        HttpServletRequest req = (HttpServletRequest) request;

        if (req.getCharacterEncoding() == null || forceRequestEncoding) {
            req.setCharacterEncoding(requestEncoding);
        }

        url = req.getRequestURI();
        method = req.getMethod();
        String qs = req.getQueryString();
        agent = req.getHeader("User-Agent");
        if (qs != null) {
            url += "?" + qs;
        }

        for (String stopUrl : dropUrls) { // does any stopUrl match url
            if (url.indexOf(stopUrl) != -1) {
                dropped = true;
                break; // stop searching
            }
        }

        if (!dropped) {
            if (ndcEnabled) {
                if (ndcAddress) {
                    String forwarded = req.getHeader("X-Forwarded-For");
                    if (forwarded != null) {
                        remoteAddress = forwarded;
                    } else {
                        remoteAddress = request.getRemoteAddr();
                    }
                }
                if (ndcSession) {
                    HttpSession session = req.getSession(false); // do not create
                    if (session != null) {
                        sessionId = session.getId();
                        String sessOID = (String) session.getAttribute("USER_ID_LOG");
                        uid = sessOID == null ? "0" : sessOID;
                    }
                }
            }
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request start ").append(method).append(" ").append(url).append(" UA=").append(agent);
            logger.info(msg.toString());
            start = System.currentTimeMillis();
        }

        filterChain.doFilter(request, response);
    } catch (IOException e) {
        throwable = e;
        throw e;
    } catch (ServletException e) {
        if (e.getRootCause() != null) {
            throwable = e.getRootCause();
        } else {
            throwable = e;
        }
        throw e;
    } catch (Throwable e) { // be sure to get all errors
        throwable = e;
        throw new ServletException(e);
    } finally {
        if (!dropped) {
            long time = System.currentTimeMillis() - start;
            StringBuilder msg = simulateNDC(remoteAddress, sessionId, uid);
            msg.append("request done ").append(method).append(" ");
            msg.append(url).append(" time=").append(time).append("ms");

            if (throwable == null) {
                logger.info(msg.toString());
            } else {
                String name = throwable.getClass().getSimpleName();
                msg.append(" ex=").append(name);
                msg.append(" msg=").append(throwable.getMessage());
                if (name.equals("ViewExpiredException") || name.equals("ClientAbortException")) {
                    logger.warn(msg.toString());
                } else {
                    msg.append(" UA=").append(agent); // also log agent in error case
                    logger.error(msg.toString());
                }
            }
        }
    }
}