List of usage examples for javax.servlet ServletRequest getRemoteAddr
public String getRemoteAddr();
From source file:com.web.mavenproject6.controller.UserController.java
@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST) @Transactional//from ww w.java 2s.c om public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result, @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField, @RequestParam(value = "recaptcha_response_field", required = false) String responseField, ServletRequest servletRequest) throws GeneralSecurityException { if (reCaptcha != null) { String remoteAdress = servletRequest.getRemoteAddr(); ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField, responseField); if (!reCaptchaResponse.isValid()) { this.create(model); return "thy/public/signup"; } } if (!result.hasErrors()) { if (userService.isUserExistByEmail(form.getEmail())) { FieldError fieldError = new FieldError("user", "email", "email already exists"); result.addError(fieldError); return "thy/public/signup"; } if (userService.isUserExistByLogin(form.getEmail())) { FieldError fieldError = new FieldError("user", "username", "login already exists"); result.addError(fieldError); return "thy/public/signup"; } Users user = new Users(); user.setLogin(form.getUsername()); user.setEmail(form.getEmail()); user.setEnabled(false); user.setPassword(form.getPassword()); Role role = new Role(); role.setUser(user); role.setRole(2); SecurityCode securityCode = new SecurityCode(); securityCode.setUser(user); securityCode.setTimeRequest(new Date()); securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT); securityCode.setCode(SecureUtility.generateRandomCode()); user.setRole(role); user.setSecurityCode(securityCode); personal person = new personal(); person.setUser(user); person.setPhoto(new byte[1]); user.setPerson(person); userService.save(user); /* for generate accessNumber by userId */ user = userService.getRepository().findUserByEmail(user.getEmail()); person = user.getPerson(); person.setAccessNumber(formatNum("" + user.getId())); user.setPerson(person); userService.save(user); securityCodeRepository.save(securityCode); mailSenderService.sendAuthorizationMail(user, user.getSecurityCode()); } else { this.create(model); return "thy/public/signup"; } return "thy/public/mailSent"; }
From source file:com.ayu.filter.CheckFilter.java
/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) *///from ww w . jav a 2 s. c om public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String str = req.getHeader("X-FORWARDED-FOR"); if (str == null) { str = request.getRemoteAddr(); } if (req.getServletContext().getAttribute("regService") == null) { req.getServletContext().setAttribute("regService", regService); } if (lruCache.map.isEmpty()) { //System.out.println("It is empty"); lruCache.map.put(str, new Timer(db.time)); chain.doFilter(request, response); } if (lruCache.map.containsKey(str)) { t = lruCache.map.get(str); t.count++; lruCache.map.put(str, t); } else { lruCache.map.put(str, new Timer(db.time)); } /** for (Map.Entry<String,Timer> e : lruCache.getAll()){ if(e.getKey().equals(str)) { t = e.getValue(); e.getValue().count++; lruCache.map.put(str,t); } else { if(lruCache.map.containsKey(str)) { t1 = lruCache.map.get(str); t1.count++; lruCache.map.put(str,t1); } else{ //lruCache.map.remove(e.getKey()); lruCache.map.put(str,new Timer()); } } }**/ if (t.count > timer) { time = System.currentTimeMillis(); //System.out.println(t.check(time)+"1"); if (t.check(time) == true) { //System.out.println("OK"); if (req.getServletContext().getAttribute(str) == null) { req.getServletContext().setAttribute(str, str); regService.registerUser(str, new Date().toString(), "DDOS Attacks", "test"); regService.camCall(str); regService.sendSSLMail("An Attack Has Occured.Please Check your System for DDOS attacks", "clouddefenceids@gmail.com"); lruCache.map.put(str, new Timer(db.time)); //System.out.println((String) req.getServletContext().getAttribute("IP")); //System.out.println(t.check(time)+"2"); res.sendError(HttpServletResponse.SC_FORBIDDEN, "You Are Perceived as a Threat"); } else { /*regService.registerUser(str,new Date().toString()); lruCache.map.put(str,new Timer(db.time));//This will add to database even if it attacked even once.. So not reqd to save resources as attacker is in DB */ chain.doFilter(request, response); } } else if (t.check(time) == false) { //System.out.println("Not Ok"); //System.out.println(t.check(time)+"3"); lruCache.map.put(str, new Timer(db.time)); //System.out.println(new Timer().count); chain.doFilter(request, response); } } else { //System.out.println(t.check(time)+"4"); // pass the request along the filter chain chain.doFilter(request, response); } }
From source file:be.bittich.quote.security.AuthenticationTokenProcessingFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = this.getAsHttpRequest(request); String authToken = extractAuthTokenFromRequest(httpRequest); String username = tokenService.getUsernameFromToken(authToken); if (username != null) { UserDetails userDetails = this.userService.loadUserByUsername(username); if (tokenService.validateToken(authToken, request.getRemoteAddr(), userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest)); SecurityContextHolder.getContext().setAuthentication(authentication); }//w ww .j av a 2 s .co m } chain.doFilter(request, response); }
From source file:org.openmrs.module.fhir.filter.AuthorizationFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *//*from w ww . j a v a 2s. c om*/ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // check the IP address first. If its not valid, return a 403 if (false) { // the ip address is not valid, set a 403 http error code HttpServletResponse httpresponse = (HttpServletResponse) response; httpresponse.sendError(HttpServletResponse.SC_FORBIDDEN, "IP address '" + request.getRemoteAddr() + "' is not authorized"); } // skip if the session has timed out, we're already authenticated, or it's not an HTTP request if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Session timed out"); } if (!Context.isAuthenticated()) { String basicAuth = httpRequest.getHeader("Authorization"); if (basicAuth != null) { // this is "Basic ${base64encode(username + ":" + password)}" try { basicAuth = basicAuth.substring(6); // remove the leading "Basic " String decoded = new String(Base64.decodeBase64(basicAuth), Charset.forName("UTF-8")); String[] userAndPass = decoded.split(":"); Context.authenticate(userAndPass[0], userAndPass[1]); if (log.isDebugEnabled()) { log.debug("authenticated " + userAndPass[0]); } } catch (Exception ex) { // This filter never stops execution. If the user failed to // authenticate, that will be caught later. } } } } // continue with the filter chain in all circumstances chain.doFilter(request, response); }
From source file:eu.freme.broker.tools.ratelimiter.RateLimitingFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (rateLimiterEnabled) { HttpServletRequest request = (HttpServletRequest) req; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); username = auth.getName();/* w w w . ja v a 2 s .c o m*/ if (username.equals("anonymousUser")) { username = req.getRemoteAddr(); } else { User user = ((User) auth.getPrincipal()); username = user.getName(); } userRole = ((SimpleGrantedAuthority) auth.getAuthorities().toArray()[0]).getAuthority(); long size = req.getContentLength(); if (size == 0) { try { size = request.getHeader("input").length(); } catch (NullPointerException e) { //Then the size is truly 0 } } try { rateLimiterInMemory.addToStoredRequests(username, new Date().getTime(), size, request.getRequestURI(), userRole); } catch (TooManyRequestsException e) { HttpServletResponse response = (HttpServletResponse) res; exceptionHandlerService.writeExceptionToResponse(request, response, e); return; } } chain.doFilter(req, res); }
From source file:com.thoughtworks.go.server.security.PerformanceLoggingFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); try {/*from ww w . j a v a2 s . c o m*/ filterChain.doFilter(servletRequest, servletResponse); } finally { if (logRequestTimings) { long amountOfTimeItTookInMilliseconds = System.currentTimeMillis() - start; String requestURI = ((HttpServletRequest) servletRequest).getRequestURI(); String requestor = servletRequest.getRemoteAddr(); com.thoughtworks.go.server.util.ServletResponse response = ServletHelper.getInstance() .getResponse(servletResponse); int status = response.getStatus(); long contentCount = response.getContentCount(); webRequestPerformanceLogger.logRequest(requestURI, requestor, status, contentCount, amountOfTimeItTookInMilliseconds); LOGGER.warn(requestURI + " took: " + amountOfTimeItTookInMilliseconds + " ms"); } } }
From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.JIPortletAuthenticationProcessingFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Trusted Host Authentication."); }//w w w. j a v a 2 s . com String incomingIPAddress = request.getRemoteAddr(); // if not from trusted host, skip this filter totally if ((incomingIPAddress == null) || (!isFromTrustedHost(incomingIPAddress))) { chain.doFilter(request, response); return; } if (logger.isDebugEnabled()) { logger.debug("Requested from Trusted Host IP:" + incomingIPAddress); } List roleList = new ArrayList(); if (!(request instanceof HttpServletRequest)) { throw new ServletException("Can only process HttpServletRequest"); } if (!(response instanceof HttpServletResponse)) { throw new ServletException("Can only process HttpServletResponse"); } HttpServletRequest httpRequest = (HttpServletRequest) request; Credentials credentials = getUserCredentials(httpRequest); String userName = credentials.getUserName(); String password = credentials.getPassword(); if ((userName == null) || (userName.trim().length() == 0)) { chain.doFilter(request, response); return; } // skip any actions when the authentication object already exists. Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); if ((existingAuth != null) && (existingAuth.getName().equals(userName)) && (existingAuth.isAuthenticated())) { // if already authenticated, set the trusted host flag so that // subsequent filters (such as the Basic auth filter) know it's a // portlet authentication request.setAttribute("fromTrustedHost", "true"); chain.doFilter(request, response); return; } // starting the flow // user exist if (doesUserExist(userName)) { // is it an internal user if (isInternalUser(userName)) { String oldPassword = getUserPaswordFromRepository(userName); // update password if they are different if (!haveSamePassword(oldPassword, password)) { updatePassword(userName, password); if (logger.isDebugEnabled()) { logger.debug("Updated Password for User:" + userName); } } } // get list of role roleList = getUserRoleList(userName); } else { if (logger.isDebugEnabled()) { logger.debug("Created New User:" + userName); } // create an internal user roleList.add("ROLE_USER"); roleList.add("ROLE_PORTLET"); createUserWithRoles(userName, password, roleList, false); } SecurityContextHolder.getContext() .setAuthentication(createAuthenticationObject(userName, password, roleList, request)); // it's authenticated thru trusted host request.setAttribute("fromTrustedHost", "true"); if (logger.isDebugEnabled()) { logger.debug("Created Authentication Object within JIPortletAuthenticationProcessingFilter"); } chain.doFilter(request, response); }
From source file:com.stormpath.spring.boot.examples.filter.ReCaptchaFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !("POST".equalsIgnoreCase(((HttpServletRequest) req).getMethod()))) { chain.doFilter(req, res);/*www .j a v a2 s . c o m*/ return; } PostMethod method = new PostMethod(RECAPTCHA_URL); method.addParameter("secret", RECAPTCHA_SECRET); method.addParameter("response", req.getParameter(RECAPTCHA_RESPONSE_PARAM)); method.addParameter("remoteip", req.getRemoteAddr()); HttpClient client = new HttpClient(); client.executeMethod(method); BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String readLine; StringBuffer response = new StringBuffer(); while (((readLine = br.readLine()) != null)) { response.append(readLine); } JSONObject jsonObject = new JSONObject(response.toString()); boolean success = jsonObject.getBoolean("success"); if (success) { chain.doFilter(req, res); } else { ((HttpServletResponse) res).sendError(HttpStatus.BAD_REQUEST.value(), "Bad ReCaptcha"); } }
From source file:com.earldouglas.filtre.Filtre.java
private void logResult(ServletRequest servletRequest, boolean accessGranted) { StringBuffer logStringBuffer = new StringBuffer(); logStringBuffer.append("Access "); if (servletRequest instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; logStringBuffer.append(" to '"); logStringBuffer.append(httpServletRequest.getRequestURI()); logStringBuffer.append("' "); }/* www . j a v a2s .c om*/ logStringBuffer.append("from "); logStringBuffer.append(servletRequest.getRemoteAddr()); logStringBuffer.append(" "); if (accessGranted) { logStringBuffer.append("granted."); } else { logStringBuffer.append("denied."); } log.info(logStringBuffer); }