Example usage for javax.servlet.http HttpServletRequest getRemoteAddr

List of usage examples for javax.servlet.http HttpServletRequest getRemoteAddr

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest 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:com.qut.middleware.esoe.sso.servlet.SSOServlet.java

private void doRequest(HttpServletRequest request, HttpServletResponse response, RequestMethod method)
        throws ServletException, IOException {
    SSOProcessorData data;/*from w  w  w  . j a  v a2  s  . c  o m*/

    data = (SSOProcessorData) request.getSession().getAttribute(SSOProcessorData.SESSION_NAME);

    String remoteAddress = request.getRemoteAddr();

    this.logger.debug("[SSO for {}] SSOServlet got {} request. SSO processor data element was {}",
            new Object[] { remoteAddress, method.toString(), data == null ? "null" : "not null" });

    if (data == null) {
        data = new SSOProcessorDataImpl();
        request.getSession().setAttribute(SSOProcessorData.SESSION_NAME, data);
    }

    data.setHttpRequest(request);
    data.setHttpResponse(response);
    data.setRequestMethod(method);

    String oldRemoteAddress = data.getRemoteAddress();
    if (oldRemoteAddress != null) {
        if (!oldRemoteAddress.equals(remoteAddress)) {
            this.logger.warn("[SSO for {}] IP address changed. Old address was: {}", remoteAddress,
                    oldRemoteAddress);
        }
    }

    data.setRemoteAddress(remoteAddress);

    try {
        SSOProcessor.result result = this.ssoProcessor.execute(data);
        this.logger.debug("[SSO for {}] SSOProcessor returned a result of {}",
                new Object[] { remoteAddress, String.valueOf(result) });
    } catch (SSOException e) {
        if (!data.isResponded()) {
            InetAddress inetAddress = Inet4Address.getByName(remoteAddress);
            String code = CalendarUtils.generateXMLCalendar().toString() + "-"
                    + new String(Hex.encodeHex(inetAddress.getAddress()));

            this.logger.error("[SSO for {}] {} Error occurred in SSOServlet.doPost. Exception was: {}", code,
                    e.getMessage());
            this.logger.debug(code + " Error occurred in SSOServlet.doPost. Exception follows", e);
            throw new ServletException(
                    "An error occurred during the sign-on process, and the session could not be established. Instance error is: "
                            + code);
        }
    }
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected Boolean logRequest(HttpServletRequest request, Event event, Identifier pid) {
    request.getRemoteHost();//from www .  j  a  v a  2 s  .  c o m
    LogEntry logEntry = new LogEntry();
    logEntry.setIpAddress(request.getRemoteAddr());

    logEntry.setUserAgent(request.getHeader("User-Agent"));

    logEntry.getNodeIdentifier();
    Subject subject = new Subject();
    subject.setValue(org.dataone.service.util.Constants.SUBJECT_PUBLIC);
    logEntry.setSubject(subject);
    logEntry.setDateLogged(new Date());

    logEntry.setIdentifier(pid);

    getDataoneLogger().add(logEntry);
    return Boolean.TRUE;
}

From source file:com.serotonin.m2m2.web.filter.LoggedInFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    // Assume an http request.
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (maxUniqueIps != -1) {
        // Check the list of IP addresses. If this is a new IP, and there
        // are no more available slots, deny the
        // request.
        String ip = request.getRemoteAddr();
        if (!usedIpAddresses.contains(ip)) {
            // This is a new IP address. Check if the limit is exceeded.
            if (usedIpAddresses.size() >= maxUniqueIps) {
                // Deny the request.
                LOGGER.info(//from  ww w .j a  v a  2  s . c o m
                        "Denying access to request from IP " + ip + ". Used IP addresses: " + usedIpAddresses);
                response.sendRedirect(exceededIpLimitUrl);
                return;
            }

            // Otherwise we add the address and continue.
            usedIpAddresses.add(ip);
        }
    }

    boolean loggedIn = true;
    User user = Common.getUser(request);
    if (user == null)
        loggedIn = false;
    else {
        for (AuthenticationDefinition def : ModuleRegistry.getDefinitions(AuthenticationDefinition.class)) {
            loggedIn = def.isAuthenticated(request, response, user);
            if (!loggedIn)
                break;
        }
    }

    if (!loggedIn) {
        LOGGER.info("Denying access to secure page for session id " + request.getSession().getId() + ", uri="
                + request.getRequestURI());

        String forwardUri = DefaultPagesDefinition.getLoginUri(request, response);
        response.sendRedirect(forwardUri);
        return;
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.taverna.server.master.identity.WorkflowInternalAuthProvider.java

/**
 * Check that the authentication request is actually valid for the given
 * user record./*  w ww . ja  v  a2 s  . c  o m*/
 * 
 * @param userRecord
 *            as retrieved from the
 *            {@link #retrieveUser(String, UsernamePasswordAuthenticationToken)}
 *            or <code>UserCache</code>
 * @param principal
 *            the principal that is trying to authenticate (and that we're
 *            trying to bind)
 * @param credentials
 *            the credentials (e.g., password) presented by the principal
 * 
 * @throws AuthenticationException
 *             AuthenticationException if the credentials could not be
 *             validated (generally a <code>BadCredentialsException</code>,
 *             an <code>AuthenticationServiceException</code>)
 * @throws Exception
 *             If something goes wrong. Will be logged and converted to a
 *             generic AuthenticationException.
 */
protected void additionalAuthenticationChecks(UserDetails userRecord, @Nonnull Object principal,
        @Nonnull Object credentials) throws Exception {
    @Nonnull
    HttpServletRequest req = ((ServletRequestAttributes) currentRequestAttributes()).getRequest();

    // Are we coming from a "local" address?
    if (!req.getLocalAddr().equals(req.getRemoteAddr()) && !authorizedAddresses.contains(req.getRemoteAddr())) {
        if (logDecisions)
            log.info("attempt to use workflow magic token from untrusted address:" + " token="
                    + userRecord.getUsername() + ", address=" + req.getRemoteAddr());
        throw new BadCredentialsException("bad login token");
    }

    // Does the password match?
    if (!credentials.equals(userRecord.getPassword())) {
        if (logDecisions)
            log.info("workflow magic token is untrusted due to password mismatch:" + " wanted="
                    + userRecord.getPassword() + ", got=" + credentials);
        throw new BadCredentialsException("bad login token");
    }

    if (logDecisions)
        log.info("granted role " + SELF + " to user " + userRecord.getUsername());
}

From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

private Session getSessionFromRequest(HttpServletRequest req) throws ServletException {
    String remoteIp = req.getRemoteAddr();
    Cookie cookie = getCookieByName(req, SESSION_ID_NAME);
    String sessionId = null;/*from   w  w  w. j a v  a 2  s .c  o  m*/

    if (cookie != null) {
        sessionId = cookie.getValue();
    }

    if (sessionId == null && hasParam(req, "session.id")) {
        sessionId = getParam(req, "session.id");
    }
    return getSessionFromSessionId(sessionId, remoteIp);
}

From source file:com.cloudbees.demo.beesshop.web.ProductController.java

@RequestMapping(value = "/product/{id}/comment", method = RequestMethod.POST)
@Transactional//from   w  ww.j a va  2  s. co  m
public String addComment(@PathVariable long id, @RequestParam("comment") String comment,
        HttpServletRequest request) {

    Product product = productRepository.get(id);
    if (product == null) {
        throw new ProductNotFoundException(id);
    }
    logger.debug("Add comment: '{}' to {}", comment, product);
    product.addComment(comment, request.getRemoteAddr());
    productRepository.update(product);

    return "redirect:/product/{id}";
}

From source file:com.streamsets.pipeline.stage.origin.ipctokafka.IpcToKafkaServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER);
    if (!configs.appId.equals(appId)) {
        LOG.warn("Validation from '{}' invalid appId '{}', rejected", req.getRemoteAddr(), appId);
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
    } else {/* w w w. j ava  2  s  .c om*/
        LOG.debug("Validation from '{}', OK", req.getRemoteAddr());
        resp.setHeader(Constants.X_SDC_PING_HEADER, Constants.X_SDC_PING_VALUE);
        resp.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:com.inkubator.sms.gateway.util.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException {
    try {//from   w  w w  .j  a v a2s  .co m
        LoginHistory loginHistory = new LoginHistory();
        loginHistory.setLanguange((String) FacesUtil.getSessionAttribute(SMSGATEWAY.BAHASA_ACTIVE));
        String number = RandomNumberUtil.getRandomNumber(15);
        loginHistory.setId(Long.parseLong(number));
        loginHistory.setIpAddress(request.getRemoteAddr());
        loginHistory.setLoginDate(new Date());
        loginHistory.setUserName(UserInfoUtil.getUserName());
        this.loginHistoryService.save(loginHistory);
        LOGGER.info(authentication.getName() + " Success Login");
        response.sendRedirect(request.getContextPath() + "/protected/home.htm");
    } catch (Exception ex) {
        LOGGER.error("Error", ex);
    }

}

From source file:cn.edu.zjnu.acm.judge.config.SecurityConfiguration.java

private void saveLoginLog(HttpServletRequest request, boolean success) {
    String userId = Optional.ofNullable(request.getParameter("user_id1")).orElse("");
    String password = Optional.ofNullable(request.getParameter("password1")).orElse("");
    loginlogService.save(LoginLog.builder().user(userId).password(passwordConfuser.confuse(password))
            .ip(request.getRemoteAddr()).success(success).build());
    if (success) {
        Optional.ofNullable(userMapper.findOne(userId)).ifPresent(user -> {
            userMapper.update(user.toBuilder().accesstime(Instant.now()).ip(request.getRemoteAddr()).build());
        });/*from w  w  w  . j av  a2s .c o  m*/
    }
}

From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java

/**
 * The service method from HttpServlet, performs handling of all
 * HTTP-requests independent of their method. Requests and responses within
 * the method can be distinguished by belonging to the "frontend" (i.e. the
 * client connecting to the proxy) or the "backend" (the server being
 * contacted on behalf of the client)//from   www .ja va  2s . c o m
 *
 * @param frontendRequest Request coming in from the client
 * @param frontendResponse Response being returned to the client
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse)
        throws ServletException, IOException {
    log(LogService.LOG_INFO,
            "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort()
                    + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " "
                    + frontendRequest.getRequestURI());

    if (targetBaseUri == null) {
        // FIXME return status page
        return;
    }

    //////////////////// Setup backend request
    final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return frontendRequest.getMethod();
        }
    };
    try {
        backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI());
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }

    //////////////////// Copy headers to backend request
    final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames();
    while (frontendHeaderNames.hasMoreElements()) {
        final String headerName = frontendHeaderNames.nextElement();
        final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName);
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            if (!headerName.equalsIgnoreCase("Content-Length")) {
                backendRequest.setHeader(headerName, headerValue);
            }
        }
    }

    //////////////////// Copy Entity - if any
    final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        backendRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }

    //////////////////// Execute request to backend
    try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) {
        frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode());

        // Copy back headers
        final Header[] backendHeaders = backendResponse.getAllHeaders();
        final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length);
        for (Header header : backendHeaders) {
            if (backendHeaderNames.add(header.getName())) {
                frontendResponse.setHeader(header.getName(), header.getValue());
            } else {
                frontendResponse.addHeader(header.getName(), header.getValue());
            }
        }

        final ServletOutputStream outStream = frontendResponse.getOutputStream();

        // Copy back entity
        final HttpEntity entity = backendResponse.getEntity();
        if (entity != null) {
            try (InputStream inStream = entity.getContent()) {
                IOUtils.copy(inStream, outStream);
            }
        }
        outStream.flush();
    }
}