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:org.apache.hadoop.security.AuthenticationWithProxyUserFilter.java

/**
 * This method provide the ability to do pre/post tasks
 * in filter chain. Override this method to authorize
 * proxy user between AuthenticationFilter and next filter.
 * @param filterChain the filter chain object.
 * @param request the request object.//from w  ww .  j  ava 2  s .c o m
 * @param response the response object.
 *
 * @throws IOException
 * @throws ServletException
 */
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // authorize proxy user before calling next filter.
    String proxyUser = getDoAs(request);
    if (proxyUser != null) {
        UserGroupInformation realUser = UserGroupInformation.createRemoteUser(request.getRemoteUser());
        UserGroupInformation proxyUserInfo = UserGroupInformation.createProxyUser(proxyUser, realUser);

        try {
            ProxyUsers.authorize(proxyUserInfo, request.getRemoteAddr());
        } catch (AuthorizationException ex) {
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
            // stop filter chain if there is an Authorization Exception.
            return;
        }

        final UserGroupInformation finalProxyUser = proxyUserInfo;
        // Change the remote user after proxy user is authorized.
        request = new HttpServletRequestWrapper(request) {
            @Override
            public String getRemoteUser() {
                return finalProxyUser.getUserName();
            }
        };

    }
    filterChain.doFilter(request, response);
}

From source file:com.alfaariss.oa.sso.web.profile.ssoquery.SSOQueryProfile.java

/**
 * @see com.alfaariss.oa.api.IService#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from ww w.  jav a  2s.c  o  m*/
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    try {
        if (!_bEnabled) {
            _logger.debug("Component is disabled");
            throw new UserException(UserEvent.INTERNAL_ERROR);
        }

        _logger.debug("Performing 'sso query' request sent from IP: " + servletRequest.getRemoteAddr());

        String responseUrl = servletRequest.getParameter(PARAM_RESPONSE_URL);
        if (responseUrl == null) {
            _logger.debug("No parameter '" + PARAM_RESPONSE_URL + "' available in request");
            throw new UserException(UserEvent.REQUEST_INVALID);
        }

        if (_whitelist != null) {
            try {
                URL urlResponse = new URL(responseUrl);

                if (!_whitelist.isWhitelisted(urlResponse.getHost())) {
                    _logger.debug("Hostname isn't whitelisted: " + urlResponse.getHost());
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
            } catch (MalformedURLException e) {
                StringBuffer sbError = new StringBuffer("Invalid parameter '");
                sbError.append(PARAM_RESPONSE_URL);
                sbError.append("' available in request: ");
                sbError.append(responseUrl);
                _logger.debug(sbError.toString());

                throw new UserException(UserEvent.REQUEST_INVALID);
            }
        }

        String sResult = "false";
        String sTGTCookie = _cookieTool.getCookieValue(WebSSOServlet.TGT_COOKIE_NAME, servletRequest);
        if (sTGTCookie != null) {
            ITGT tgt = _tgtFactory.retrieve(sTGTCookie);
            if (tgt != null && !tgt.isExpired())
                sResult = "true";
        }

        StringBuffer sbRedirect = new StringBuffer(responseUrl);
        if (responseUrl.contains("?"))
            sbRedirect.append("&");
        else
            sbRedirect.append("?");

        sbRedirect.append(PARAM_RESULT);
        sbRedirect.append("=");
        sbRedirect.append(sResult);

        _eventLogger.info(new RequestorEventLogItem(null, sTGTCookie, null, RequestorEvent.QUERY_SUCCESSFUL,
                null, servletRequest.getRemoteAddr(), null, this, sResult));

        _logger.debug("Redirecting user to: " + sbRedirect.toString());
        servletResponse.sendRedirect(sbRedirect.toString());
    } catch (UserException e) {
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.debug("Could not respond", e1);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (Exception e) {
        _logger.fatal("Internal error during sso request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

private void setXForwardedForHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest) {
    if (doForwardIP) {
        String headerName = "X-Forwarded-For";
        String newHeader = servletRequest.getRemoteAddr();
        String existingHeader = servletRequest.getHeader(headerName);
        if (existingHeader != null) {
            newHeader = existingHeader + ", " + newHeader;
        }//from  w  w  w.  j  ava  2  s  .  c  o m
        proxyRequest.setHeader(headerName, newHeader);
    }
}

From source file:com.google.identitytoolkit.GitkitClient.java

private JSONObject buildPasswordResetRequest(HttpServletRequest req) throws JSONException {
    return new JSONObject().put("email", req.getParameter("email")).put("userIp", req.getRemoteAddr())
            .put("challenge", req.getParameter("challenge")).put("captchaResp", req.getParameter("response"))
            .put("requestType", "PASSWORD_RESET");
}

From source file:md.ibanc.rm.spring.service.SingInOutSessionsServiceImpl.java

@Override
@Transactional/* w  w w  .ja  v  a2  s .  c o m*/
public SingInOutSessions save(String guidId, Customers customers, HttpServletRequest request) {
    Sessions sessions = new Sessions();

    Calendar cal = Calendar.getInstance();
    Timestamp timestamp = new Timestamp(cal.getTimeInMillis());

    sessions.setCreatedAt(timestamp);
    sessions.setSessionUid(guidId);

    sessionsDAO.save(sessions);

    SingInOutSessions singInOutSessions = new SingInOutSessions();
    singInOutSessions.setCustomers(customers);
    singInOutSessions.setSessions(sessions);
    singInOutSessions.setSingInDate(timestamp);
    singInOutSessions.setIp(request.getRemoteAddr());
    singInOutSessions.setLocation(request.getRemoteUser());

    singInOutSessionsDAO.save(singInOutSessions);
    return singInOutSessions;

}

From source file:br.com.siprot.framework.servlet.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());/*  w  w w  .jav a 2s.co  m*/

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        //bloco de tratamento para excecao tratada
        if (e instanceof FacesException) {
            try {
                ErrorHandler.handleException(facesContext, (Exception) e);
                _lifecycle.render(facesContext);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
        //fim do bloco de  tratamento
        else if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}

From source file:fr.paris.lutece.plugins.mylutece.modules.openid.authentication.OpenIDAuthentication.java

/**
 * processing the authentication response
 * @param request The HTTP request//from ww  w  .  j  a v a  2s . co  m
 * @return The URL depending of the result
 */
public String verifyResponse(HttpServletRequest request) {
    String strReturnUrl = getMessageUrl(request, MESSAGE_KEY_AUTHENTICATION_FAILED);

    _logger.debug(
            "Provider callback - host : " + request.getRemoteHost() + " - IP : " + request.getRemoteAddr());

    OpenIDUser user = null;

    try {
        // extract the parameters from the authentication response
        // (which comes in as a HTTP request from the OpenID provider)
        ParameterList response = new ParameterList(request.getParameterMap());

        // retrieve the previously stored discovery information
        DiscoveryInformation discovered = (DiscoveryInformation) request.getSession()
                .getAttribute("openid-disc");

        // extract the receiving URL from the HTTP request
        StringBuffer receivingURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if ((queryString != null) && (queryString.length() > 0)) {
            receivingURL.append("?").append(request.getQueryString());
        }

        // verify the response; ConsumerManager needs to be the same
        // (static) instance used to place the authentication request
        VerificationResult verification = _manager.verify(receivingURL.toString(), response, discovered);

        // examine the verification result and extract the verified identifier
        Identifier verified = verification.getVerifiedId();
        _logger.debug("Authentication verification  : " + verified);

        if (verified != null) {
            user = new OpenIDUser(verified.getIdentifier(), this);

            AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

            if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
                _logger.debug("Authentication successfull - identifier : " + verified.getIdentifier());

                FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

                for (String strKey : (Set<String>) fetchResp.getAttributes().keySet()) {
                    _logger.debug(
                            "Attribute " + strKey + " - value : " + fetchResp.getAttributes().get(strKey));
                }

                String strFirstName = (String) fetchResp.getAttributes().get(ATTRIBUTE_FIRST_NAME);
                String strLastName = (String) fetchResp.getAttributes().get(ATTRIBUTE_LAST_NAME);
                List emails = fetchResp.getAttributeValues(ATTRIBUTE_EMAIL);
                String email = (String) emails.get(0);

                user.setUserInfo(LuteceUser.NAME_GIVEN, strFirstName);
                user.setUserInfo(LuteceUser.NAME_FAMILY, strLastName);
                user.setUserInfo(LuteceUser.BUSINESS_INFO_ONLINE_EMAIL, email);
            }

            SecurityService.getInstance().registerUser(request, user);

            strReturnUrl = AppPathService.getBaseUrl(request) + AppPathService.getPortalUrl(); // success
        }
    } catch (OpenIDException e) {
        _logger.error("OpenId Error in provider response : " + e.getMessage(), e);
    }

    return strReturnUrl;
}

From source file:be.bittich.quote.controller.impl.AuthControllerImpl.java

@Override
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)//from w ww. j av  a  2 s . c o m
public SecurityToken authenticate(@Context HttpServletRequest request, @RequestBody @Valid UserVO userVO) {
    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            userVO.getUsername(), userVO.getPassword());

    Authentication authentication = authenticationManager.authenticate(authenticationToken);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    UserDetails userDetails = this.userService.loadUserByUsername(userVO.getUsername());

    SecurityToken createToken = tokenService.createToken(userDetails, request.getRemoteAddr());
    return createToken;
}

From source file:com.photon.phresco.service.rest.api.ProjectService.java

private void buildCreateLogMessage(HttpServletRequest request, ProjectInfo projectInfo)
        throws PhrescoException {
    try {//from ww w.ja va 2  s.  co  m
        if (isDebugEnabled) {
            for (ApplicationInfo applicationInfo : projectInfo.getAppInfos()) {
                LOGGER.warn("ProjectService.createProject", "remoteAddress=" + request.getRemoteAddr(),
                        "technology=" + applicationInfo.getTechInfo().getName(),
                        "user=" + request.getParameter("userId"),
                        "authType=" + request.getParameter("authType"),
                        "customer=" + getCustomerNameById(projectInfo.getCustomerIds().get(0)),
                        "action=" + "CREATE", "endpoint=" + request.getRequestURI(),
                        "method=" + request.getMethod(),
                        "projectCode=" + "\"" + projectInfo.getProjectCode() + "\"",
                        "totalNoOfApps=" + projectInfo.getNoOfApps(), getApplications(projectInfo));
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
}

From source file:com.photon.phresco.service.rest.api.ProjectService.java

private void buildUpdateLogMessage(HttpServletRequest request, ProjectInfo projectInfo)
        throws PhrescoException {
    try {// w ww .  j  ava2 s. co  m
        if (isDebugEnabled) {
            for (ApplicationInfo applicationInfo : projectInfo.getAppInfos()) {
                LOGGER.warn("ProjectService.updateProject", "remoteAddress=" + request.getRemoteAddr(),
                        "technology=" + applicationInfo.getTechInfo().getName(),
                        "user=" + request.getParameter("userId"),
                        "authType=" + request.getParameter("authType"),
                        "customer=" + getCustomerNameById(projectInfo.getCustomerIds().get(0)),
                        "action=" + "UPDATE", "endpoint=" + request.getRequestURI(),
                        "method=" + request.getMethod(),
                        "projectCode=" + "\"" + projectInfo.getProjectCode() + "\"",
                        "totalNoOfApps=" + projectInfo.getNoOfApps(), getApplications(projectInfo),
                        getFeatures(applicationInfo), getJslibs(applicationInfo));
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
}