@Override public void onComplete(Result result) { final long requestTime = System.currentTimeMillis() - start; emitter.emit( new ServiceMetricEvent.Builder() .setUser2(DataSourceUtil.getMetricName(query.getDataSource())) .setUser3(String.valueOf(query.getContextPriority(0))) .setUser4(query.getType()) .setUser5(DataSourceUtil.COMMA_JOIN.join(query.getIntervals())) .setUser6(String.valueOf(query.hasFilters())) .setUser7(req.getRemoteAddr()) .setUser8(query.getId()) .setUser9(query.getDuration().toPeriod().toStandardMinutes().toString()) .build("request/time", requestTime)); try { requestLogger.log( new RequestLogLine( new DateTime(), req.getRemoteAddr(), query, new QueryStats( ImmutableMap.<String, Object>of( "request/time", requestTime, "success", true)))); } catch (Exception e) { log.error(e, "Unable to log query [%s]!", query); } super.onComplete(result); }
private boolean findOnlineUser(String userid) { HttpSession session = request.getSession(); ServletContext application = (ServletContext) session.getServletContext(); ArrayList users = (ArrayList) application.getAttribute("users"); HashMap ipUser = (HashMap) application.getAttribute("ipusers"); if (null != users && users.contains(userid)) { if (ipUser != null && ((String) ipUser.get(userid)).equals((String) request.getRemoteAddr())) { session.setAttribute("username", userid); return true; } else { return false; } } else { session.setAttribute("username", userid); if (users == null) { users = new ArrayList(); } users.add(userid); if (ipUser == null) { ipUser = new HashMap(); } ipUser.put(userid, request.getRemoteAddr()); application.setAttribute("ipusers", ipUser); application.setAttribute("users", users); return true; } }
/** * Called to change the status of the utils.ModulePlan class. Once this has been called by a valid * administrator, the utils.ModulePlan will be changed. * * @param csrfToken */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Setting IpAddress To Log and taking header for original IP if forwarded from proxy ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For")); log.debug("*** servlets.Admin.SetOpenFloor ***"); PrintWriter out = response.getWriter(); out.print(getServletInfo()); HttpSession ses = request.getSession(true); Cookie tokenCookie = Validate.getToken(request.getCookies()); Object tokenParmeter = request.getParameter("csrfToken"); if (Validate.validateAdminSession(ses, tokenCookie, tokenParmeter)) { ShepherdLogManager.setRequestIp( request.getRemoteAddr(), request.getHeader("X-Forwarded-For"), ses.getAttribute("userName").toString()); if (Validate.validateTokens(tokenCookie, tokenParmeter)) { ModulePlan.setOpenFloor(); log.debug("Open Floor Plan enabled"); out.write( "<h3 class='title'>Open Floor Plan Enabled</h3>" + "<p>Security Shepherd Users are now using an open floor plan. Refresh your browser to see these settings in effect.</p>"); } else { out.write("Error Occurred!"); } } log.debug("*** END servlets.Admin.SetOpenFloor ***"); }
@Override public void onFailure(Response response, Throwable failure) { try { final String errorMessage = failure.getMessage(); requestLogger.log( new RequestLogLine( new DateTime(), req.getRemoteAddr(), query, new QueryStats( ImmutableMap.<String, Object>of( "success", false, "exception", errorMessage == null ? "no message" : errorMessage)))); } catch (IOException logError) { log.error(logError, "Unable to log query [%s]!", query); } log.makeAlert(failure, "Exception handling request") .addData("exception", failure.toString()) .addData("query", query) .addData("peer", req.getRemoteAddr()) .emit(); super.onFailure(response, failure); }
/** * @param request * @param response @TODO refactor and optimize code for initializing handler */ public void doService(HttpServletRequest request, HttpServletResponse response) { if (response.isCommitted()) { LOG.logWarning("The response object is already committed!"); } long startTime = System.currentTimeMillis(); address = request.getRequestURL().toString(); String service = null; try { OGCWebServiceRequest ogcRequest = OGCRequestFactory.create(request); LOG.logInfo( StringTools.concat( 500, "Handling request '", ogcRequest.getId(), "' from '", request.getRemoteAddr(), "' to service: '", ogcRequest.getServiceName(), "'")); // get service from request service = ogcRequest.getServiceName().toUpperCase(); // get handler instance ServiceDispatcher handler = ServiceLookup.getInstance().getHandler(service, request.getRemoteAddr()); // dispatch request to specific handler handler.perform(ogcRequest, response); } catch (OGCWebServiceException e) { LOG.logError(e.getMessage(), e); sendException(response, e, request, service); } catch (ServiceException e) { if (e.getNestedException() instanceof OGCWebServiceException) { sendException(response, (OGCWebServiceException) e.getNestedException(), request, service); } else { sendException( response, new OGCWebServiceException(this.getClass().getName(), e.getMessage()), request, service); } LOG.logError(e.getMessage(), e); } catch (Exception e) { sendException( response, new OGCWebServiceException(this.getClass().getName(), e.getMessage()), request, service); LOG.logError(e.getMessage(), e); } if (LOG.isDebug()) { LOG.logDebug( "OGCServletController: request performed in " + Long.toString(System.currentTimeMillis() - startTime) + " milliseconds."); } }
/** Metodo responsavel por interceptar os eventos e validar o acesso as paginas do sistema. */ public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); String viewId = context.getViewRoot().getViewId(); LoginBean loginBean = context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class); if (!viewId.equals("/logout.xhtml") && !viewId.equals("/login.xhtml")) { loginBean.autenticar(); if (loginBean.getUsuarioAutenticado() != null) { ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest(); this.remoteAddress = request.getRemoteAddr(); logger.warning("Acesso permitido em " + viewId + " por " + this.remoteAddress); } else { ExternalContext externalContext = context.getExternalContext(); HttpSession httpSession = (HttpSession) externalContext.getSession(false); httpSession.invalidate(); ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest(); this.remoteAddress = request.getRemoteAddr(); if (loginBean.getUsuarioAutenticado() == null) { logger.warning("Acesso indevido em " + viewId + " por " + this.remoteAddress + "."); } } } }
@Override public AnonymousUser getAnonymousUser(HttpServletRequest request, long userId) throws PortalException, SystemException { long companyId = PortalUtil.getCompanyId(request); ServiceContext serviceContext = new ServiceContext(); serviceContext.setCompanyId(companyId); AnonymousUser anonymousUser = AnonymousUserLocalServiceUtil.fetchAnonymousUserByUserId(userId); if (anonymousUser == null) { anonymousUser = getAnonymousUserFromCookie(request); if ((anonymousUser == null) || ((anonymousUser.getUserId() != 0) && (anonymousUser.getUserId() != userId))) { anonymousUser = AnonymousUserLocalServiceUtil.addAnonymousUser( userId, request.getRemoteAddr(), null, serviceContext); } else { anonymousUser = AnonymousUserLocalServiceUtil.updateAnonymousUser( anonymousUser.getAnonymousUserId(), userId, request.getRemoteAddr(), anonymousUser.getTypeSettings(), serviceContext); } } return anonymousUser; }
public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) { String theInput = aRequest.getParameter("input"); String theSession = aRequest.getParameter("session"); String thePeerId = aRequest.getParameter("peerid"); LOGGER.debug( "Received message from peer '" + thePeerId + "' in session '" + theSession + "': " + theInput + "'" + " at remote ip '" + aRequest.getRemoteAddr() + "'"); // TODO remove when logging correctly enabled on server // System.out.println("Received message from peer '" + thePeerId + "' in session '" + // theSession + "': " + theInput + "'" ); try { // LOGGER.debug( "Concurrent requests in ProtocolServlet: " + // myConcurrentRequestCounter.incrementAndGet()); if (theSession != null && !"".equals(theSession)) { String theURL = aRequest.getRequestURL().toString(); theURL = theURL.substring(0, theURL.indexOf("/", 7) + 1); getSessionData().putProperty(theSession, "requestor.ip", aRequest.getRemoteAddr()); getSessionData() .putProperty( theSession, ProtocolServer.NETWORK_INTERFACE, HttpCommunicationInterface.getInstance()); // getSessionData().putProperty(theSession, "requestor.url", theURL); // LOGGER.debug("Remote ip '" + getSessionData().getProperty(theSession, "requestor.ip") // + "'"); // LOGGER.debug("Remote url '" + getSessionData().getProperty(theSession, // "requestor.url") + "'"); } if ("exchange".equalsIgnoreCase(theInput)) { ((RoutingProtocol) getProtocolContainer().getProtocol(RoutingProtocol.ID)) .exchangeRoutingTable(); } else if (theInput == null || "".equals(theInput)) { printDebugInfo(aRequest, aResponse, theSession); } else { getPeerIpMap().put(thePeerId, aRequest.getRemoteAddr()); String theResult = getProtocolContainer().handleCommand(theSession, theInput); aResponse.getWriter().println(theResult); } } catch (Exception e) { LOGGER.error("could not send response message ", e); } finally { // remove the session data getSessionData().clearSessionData(theSession); myConcurrentRequestCounter.decrementAndGet(); } }
public static String remoteAddr(HttpServletRequest request, boolean trustChain) { try { String remoteAddr = request.getRemoteAddr(); String x; if ((x = request.getHeader(HEADER_X_FORWARDED_FOR)) != null) return remoteAddr(x, trustChain); return remoteAddr; } catch (Exception e) { return request.getRemoteAddr(); } }
/** * This method validates input and then attempts to update the cheat sheet for the specified * module * * @param newSolution The new solution to store as a cheat sheet * @param moduleId[] The identifier of the module to update. * @param csrfToken */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Setting IpAddress To Log and taking header for original IP if forwarded from proxy ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For")); log.debug("*** servlets.Admin.CreateCheat ***"); Encoder encoder = ESAPI.encoder(); PrintWriter out = response.getWriter(); out.print(getServletInfo()); HttpSession ses = request.getSession(true); Cookie tokenCookie = Validate.getToken(request.getCookies()); Object tokenParmeter = request.getParameter("csrfToken"); if (Validate.validateAdminSession(ses, tokenCookie, tokenParmeter)) { ShepherdLogManager.setRequestIp( request.getRemoteAddr(), request.getHeader("X-Forwarded-For"), ses.getAttribute("userName").toString()); log.debug("Current User: "******"userName").toString()); if (Validate.validateTokens(tokenCookie, tokenParmeter)) { String errorMessage = null; String newSolution = request.getParameter("newSolution"); log.debug("User submitted new solution - " + newSolution); String moduleId = request.getParameter("moduleId[]"); log.debug("User submitted moduleId: " + moduleId); if (newSolution != null && !newSolution.isEmpty()) { String ApplicationRoot = getServletContext().getRealPath(""); String moduleCheck = Getter.getModuleResult(ApplicationRoot, moduleId); if (moduleCheck != null) { if (!Setter.updateCheatSheet( ApplicationRoot, moduleId, encoder.encodeForHTML(newSolution))) errorMessage = "A database level error occurred. Please contact your administrator"; } else { errorMessage = "Invalid Module submitted"; } } else { errorMessage = "Invalid Module submitted"; } String output = new String(); if (errorMessage != null) { output = "<h2 class='title'>Create Cheat Sheet Failure</h2>" + "<p>" + encoder.encodeForHTML(errorMessage) + "</p>"; } else { output = "<h2 class='title'>Create Cheat Sheet Success</h2>" + "<p>Cheat Sheet successfully created</p>"; } out.write(output); } } else { out.write("<img src='css/images/loggedOutSheep.jpg'/>"); } log.debug("*** END servlets.Admin.CreateCheat ***"); }
public long getLastModified(HttpServletRequest request) { if (Calendar.getInstance().getTimeInMillis() > 0) return Calendar.getInstance() .getTimeInMillis(); // comment this line if you want allow browser to check when resource // was last modified String userID = (String) request.getSession().getAttribute(SportletProperties.PORTLET_USER); if (userID == null || userID.equals("")) { if (DEBUG) log( "LastModifiedRequest blocked (userID=" + userID + ") !!! Request: " + request.getRequestURI() + "\nIP: " + request.getRemoteAddr() + "\n"); return Calendar.getInstance().getTimeInMillis(); } else if (!inited) { return Calendar.getInstance().getTimeInMillis(); } else { String userDirPath = secureDirPath + "/" + userID; if (!(new File(userDirPath).isDirectory())) { if (DEBUG) log( "LastModifiedRequest blocked (userDirPath=" + userDirPath + " is not directory) !!! Request: " + request.getRequestURI() + "\nIP: " + request.getRemoteAddr() + "\n"); return Calendar.getInstance().getTimeInMillis(); } else { String resourcePath = util.substitute( "s!" + request.getContextPath() + request.getServletPath() + "!!", request.getRequestURI()); File resource = new File(userDirPath + resourcePath); if (!resource.exists()) { log( "LastModifiedRequest blocked (Not found, resource=" + userDirPath + resourcePath + ") !!! Request: " + request.getRequestURI() + "\nIP: " + request.getRemoteAddr() + "\n"); return new Date().getTime(); } else { return resource.lastModified(); } } } }
public void autoSetLocation(HttpServletRequest request) { DbDao db = new DbDao(); System.out.println("RemAddr: " + request.getRemoteAddr()); System.out.println("RemHost: " + request.getRemoteHost()); String ipAddress = request.getRemoteAddr(); location = null; // db.getLocationByIp("24.68.70.242"); if (location == null) { int[] tempLoc = {-1, -1, -1, -1}; location = tempLoc; } }
@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 { LOG.debug("Validation from '{}', OK", req.getRemoteAddr()); resp.setHeader(Constants.X_SDC_PING_HEADER, Constants.X_SDC_PING_VALUE); resp.setStatus(HttpServletResponse.SC_OK); } }
private String getIp(HttpServletRequest request) { String ip = request.getRemoteAddr(); if (ip == null || ip.length() == 0) { HttpSession hs = request.getSession(); System.out.println(request.getRemoteAddr() + "_" + hs.getAttribute("loginInfo")); if (hs.getAttribute("loginInfo") != null) { // LoginInfo loginInfo = // (LoginInfo)hs.getAttribute("loginInfo"); ip = "192.168.2.1"; // loginInfo.loginhost; } } return ip; }
// FIXME - shouldn't need to pass in response private boolean register( HttpServletRequest request, HttpServletResponse response, ModelAndView next, WikiPageInfo pageInfo) throws Exception { pageInfo.setSpecial(true); pageInfo.setAction(WikiPageInfo.ACTION_REGISTER); pageInfo.setPageTitle(new WikiMessage("register.title")); String virtualWikiName = JAMWikiServlet.getVirtualWikiFromURI(request); WikiUser user = new WikiUser(); String userIdString = request.getParameter("userId"); if (StringUtils.hasText(userIdString)) { int userId = new Integer(userIdString).intValue(); if (userId > 0) user = WikiBase.getHandler().lookupWikiUser(userId); } user.setLogin(request.getParameter("login")); user.setDisplayName(request.getParameter("displayName")); user.setEmail(request.getParameter("email")); String newPassword = request.getParameter("newPassword"); if (StringUtils.hasText(newPassword)) { user.setEncodedPassword(Encryption.encrypt(newPassword)); } // FIXME - need to distinguish between add & update user.setCreateIpAddress(request.getRemoteAddr()); user.setLastLoginIpAddress(request.getRemoteAddr()); next.addObject("newuser", user); Vector errors = validate(request, user); if (errors.size() > 0) { next.addObject("errors", errors); String oldPassword = request.getParameter("oldPassword"); String confirmPassword = request.getParameter("confirmPassword"); if (oldPassword != null) next.addObject("oldPassword", oldPassword); if (newPassword != null) next.addObject("newPassword", newPassword); if (confirmPassword != null) next.addObject("confirmPassword", confirmPassword); return false; } else { WikiBase.getHandler().writeWikiUser(user); request.getSession().setAttribute(JAMWikiServlet.PARAMETER_USER, user); VirtualWiki virtualWiki = WikiBase.getHandler().lookupVirtualWiki(virtualWikiName); String topic = virtualWiki.getDefaultTopicName(); String redirect = LinkUtil.buildInternalLinkUrl(request.getContextPath(), virtualWikiName, topic); // FIXME - can a redirect be done with Spring? redirect(redirect, response); return true; } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String uri = req.getRequestURI(); log.info(req.getRemoteAddr() + "\tvisite\t" + uri); String project = req.getContextPath(); /*if (SESSION_COMPANY == null && SESSION_BUYER == null && SESSION_BRANCH==null && !uri.endsWith(project+"/logout.do")) { cookieLogin((HttpServletRequest)request, (HttpServletResponse)response); }*/ if ((project + "/").equals(uri) || (project + "/index.jsp").equals(uri)) { res.sendRedirect(req.getContextPath() + "/index.do"); // 用户未登 } if (isNeedCheck(uri, project)) { if (1 == 1) { // 如果toLogin参数存在,则登录以后跳回到原页面 String toLogin = req.getParameter("toLogin"); String returnURL = ""; if (null != toLogin) returnURL = req.getHeader("Referer"); // 用户未登 res.sendRedirect(req.getContextPath() + "/login.jsp?returnURL=" + returnURL); } else { chain.doFilter(request, response); } } else { chain.doFilter(request, response); } }
@Test public void inloggenJuist() { Medewerker medewerker = new Medewerker(); medewerker.setIdentificatie("emailadres"); medewerker.setHashWachtwoord("wachtwoord"); try { EasyMock.expect(gebruikerRepository.zoek("emailadres")).andReturn(medewerker); } catch (NietGevondenException e1) { fail(); } HttpSession httpSession = EasyMock.createMock(HttpSession.class); EasyMock.expect(servletRequest.getSession()).andReturn(httpSession); EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("1234").times(2); EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent"); EasyMock.expect(httpSession.getId()).andReturn("234"); gebruikerRepository.opslaan(medewerker); EasyMock.expectLastCall(); replayAll(); try { gebruikerService.inloggen("emailadres", "wachtwoord", "false", servletRequest); } catch (LeegVeldException | NietGevondenException | OnjuistWachtwoordException e) { fail(e.getMessage()); } verifyAll(); }
@Test public void uitloggen() { HttpSession httpSession = EasyMock.createMock(HttpSession.class); EasyMock.expect(servletRequest.getSession()).andReturn(httpSession).times(2); EasyMock.expect(httpSession.getId()).andReturn("a").times(2); EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr").times(2); EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent"); Medewerker medewerker = new Medewerker(); medewerker.setId(46L); Sessie sessie = new Sessie(); sessie.setGebruiker(medewerker); sessie.setIpadres("adr"); sessie.setSessie("a"); medewerker.getSessies().add(sessie); try { EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker); } catch (NietGevondenException e1) { } gebruikerRepository.opslaan(medewerker); EasyMock.expectLastCall(); replayAll(); EasyMock.replay(httpSession); gebruikerService.uitloggen(servletRequest); verifyAll(); EasyMock.verify(httpSession); }
@Test public void getIngelogdeGebruiker() { HttpSession httpSession = EasyMock.createMock(HttpSession.class); EasyMock.expect(servletRequest.getSession()).andReturn(httpSession); EasyMock.expect(httpSession.getId()).andReturn("a"); EasyMock.expect(servletRequest.getRemoteAddr()).andReturn("adr"); EasyMock.expect(servletRequest.getHeader("user-agent")).andReturn("agent"); Medewerker medewerker = new Medewerker(); medewerker.setId(46L); Sessie sessie = new Sessie(); sessie.setGebruiker(medewerker); sessie.setIpadres("adr"); sessie.setSessie("a"); medewerker.getSessies().add(sessie); try { EasyMock.expect(gebruikerRepository.zoekOpSessieEnIpadres("a", "adr")).andReturn(medewerker); } catch (NietGevondenException e1) { } replayAll(); EasyMock.replay(httpSession); try { assertEquals(medewerker, gebruikerService.getIngelogdeGebruiker(servletRequest)); } catch (NietIngelogdException e) { } verifyAll(); EasyMock.verify(httpSession); }
/** * Stores the audit record. * * @param request the http servlet request * @param auditService the audit service * @param currentUser the current user * @param actionName the action name * @param values the values of audit parameter records * @throws OPMException if any error occurs */ public static void audit( HttpServletRequest request, AuditService auditService, User currentUser, String actionName, List<Object[]> values) throws OPMException { AuditRecord auditRecord = new AuditRecord(); auditRecord.setUsername(currentUser.getUsername()); auditRecord.setIpAddress(request.getRemoteAddr()); auditRecord.setActionName(actionName); auditRecord.setDate(new Date()); List<AuditParameterRecord> parameters = new ArrayList<AuditParameterRecord>(); auditRecord.setParameters(parameters); for (int i = 0; i < values.size(); i++) { Object[] recordValues = values.get(i); int index = 0; AuditParameterRecord parameterRecord = new AuditParameterRecord(); parameterRecord.setItemId(Long.parseLong(recordValues[index++].toString())); parameterRecord.setItemType((String) recordValues[index++]); parameterRecord.setPropertyName((String) recordValues[index++]); parameterRecord.setPreviousValue(getString(recordValues[index++])); parameterRecord.setNewValue(getString(recordValues[index])); parameters.add(parameterRecord); } auditService.audit(auditRecord); }
// 登陆 public String login() { // 先从session中取empModel EmpModel loginEmp = null; loginEmp = getLogin(); if (loginEmp == null) { // 添加登陆ip(lastLoginIp) HttpServletRequest request = ServletActionContext.getRequest(); String loginIp = request.getHeader("x-forwarded-for"); if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("Proxy-Client-IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getHeader("WL-Proxy-Client-IP"); } if (loginIp == null || loginIp.length() == 0 || "unknown".equalsIgnoreCase(loginIp)) { loginIp = request.getRemoteAddr(); } // 根据业务层查询登陆的用户,用户名/密码是否正确 loginEmp = empEbi.login(emp.getUserName(), emp.getPwd(), loginIp); } // 判断是否查到用户 if (loginEmp != null) { // 将用户信息放入session中 putSession(EmpModel.LOGIN_EMP_INFO, loginEmp); return "loginSuccess"; } else { // 添加错误提示信息 this.addActionError("用户名/密码错误!"); return "loginFail"; } }
// test valid User, but invalid ip @Test public void testAuthenticateValidAuthButInvalidIp() throws Exception { UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl(); User dbuser = new User(); dbuser.setLogin("bob"); dbuser.setToken("smith"); dbuser.setPermissions(Permission.LIST_ALL_JOBS); ArrayList<String> allowedIps = new ArrayList<String>(); allowedIps.add("192.168.1.2"); dbuser.setAllowedIpAddresses(allowedIps); dbuser = userDAO.insert(dbuser); AuthenticatorImpl auth = new AuthenticatorImpl(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteAddr()).thenReturn("192.168.1.1"); when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER)) .thenReturn("Basic " + encodeString("bob:smith")); User u = auth.authenticate(request); assertTrue(u.getLogin() == null); assertTrue(u.getToken() == null); assertTrue(u.getPermissions() == Permission.NONE); assertTrue(u.getIpAddress().equals("192.168.1.1")); verify(request).getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER); }
/** * 获取真实IP,请求头中添加X-Real-IP * * @param request request * @return ip */ public static String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("X-Real-IP"); if (ip == null || ip == "") { ip = request.getRemoteAddr(); } return ip; }
// 获得IP地址 public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; }
public void prepare() throws Exception { logger.debug("Inside PatientProfile:prepare()"); try { WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( ServletActionContext.getServletContext()); userService = (UserService) context.getBean("userService"); auditInfoService = (AuditInfoService) context.getBean("auditInfoService"); patientService = (PatientService) context.getBean("patientService"); contactService = (ContactService) context.getBean("contactService"); logger.debug("In prepare patientService =" + patientService); // is client behind something? ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } logger.debug("client's ipAddress =" + ipAddress); Object obj = request.getSession().getAttribute("user"); if (obj != null) { userInSession = (UserVO) obj; } logger.debug("userInSession is " + userInSession.getAttributesAsString()); // path = context.getServletContext().getRealPath("/"); // String app = context.getServletContext().getContextPath(); // path = path.substring(0, path.lastIndexOf(app.split("/")[1])); } catch (Exception e) { e.printStackTrace(); } logger.debug("Completing PatientProfile:prepare()"); }
@Override @Transactional protected UserDetails processAutoLoginCookie( String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { PersistentToken token = getPersistentToken(cookieTokens); String login = token.getUser().getLogin(); // Token also matches, so login is valid. Update the token value, keeping the *same* series // number. log.debug( "Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries()); token.setTokenDate(LocalDate.now()); token.setTokenValue(generateTokenData()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to update token: ", e); throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e); } return getUserDetailsService().loadUserByUsername(login); }
/** * 获取登录用户的IP地址 * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); logger.debug("1- X-Forwarded-For ip={}", ip); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); logger.debug("2- Proxy-Client-IP ip={}", ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); logger.debug("3- WL-Proxy-Client-IP ip={}", ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); logger.debug("4- HTTP_CLIENT_IP ip={}", ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); logger.debug("5- HTTP_X_FORWARDED_FOR ip={}", ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); logger.debug("6- getRemoteAddr ip={}", ip); } if (ip.equals("0:0:0:0:0:0:0:1")) { ip = "本地"; } logger.info("finally ip={}", ip); return ip; }
@Test public void testAuthenticateValidAuthInHeaderAndUserInDataStore() throws Exception { UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl(); User dbuser = new User(); dbuser.setLogin("bob"); dbuser.setToken("smith"); dbuser.setPermissions(Permission.LIST_ALL_JOBS); dbuser = userDAO.insert(dbuser); AuthenticatorImpl auth = new AuthenticatorImpl(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteAddr()).thenReturn("192.168.1.1"); when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER)) .thenReturn("Basic " + encodeString("bob:smith")); User u = auth.authenticate(request); assertTrue(u != null); assertTrue(u.getLogin().equals("bob")); assertTrue(u.getToken().equals("smith")); assertTrue(u.getPermissions() == Permission.LIST_ALL_JOBS); assertTrue(u.getIpAddress().equals("192.168.1.1")); assertTrue(u.getId() == dbuser.getId().longValue()); verify(request).getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER); }
@GET @Path("/") @Produces("application/json") public List<Visitor> getVisitors() { visitorService.addVisitor(request.getRemoteAddr(), request.getHeader("User-Agent")); return visitorService.getVisitors(); }
@Test public void testAuthenticateValidAuthInHeaderAndUserInDataStoreButNotAuthorizedToRunAsAnotherUser() throws Exception { UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl(); User dbuser = new User(); dbuser.setLogin("bob"); dbuser.setToken("smith"); dbuser.setPermissions(Permission.LIST_ALL_JOBS); dbuser = userDAO.insert(dbuser); AuthenticatorImpl auth = new AuthenticatorImpl(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRemoteAddr()).thenReturn("192.168.1.1"); when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER)) .thenReturn("Basic " + encodeString("bob:smith")); when(request.getParameter(Constants.USER_LOGIN_TO_RUN_AS_PARAM)).thenReturn("joe"); try { auth.authenticate(request); } catch (Exception ex) { assertTrue(ex.getMessage().equals("User does not have permission to run as another user")); } }