List of usage examples for javax.servlet ServletRequest getRemoteAddr
public String getRemoteAddr();
From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java
/** * Time the processing that is performed by all subsequent filters in the * current filter stack, including the ultimately invoked servlet. * * @param request The servlet request we are processing * @param result The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs *//* w w w . j a va 2 s . c om*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; // Render the generic servlet request properties StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis()))); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); Enumeration locales = request.getLocales(); boolean first = true; while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); if (first) first = false; else writer.print(", "); writer.print(locale.toString()); } writer.println(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); writer.print(" parameter=" + name + "="); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) writer.print(", "); writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { writer.println("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie cookies[] = hrequest.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } names = hrequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); } writer.println("============================================="); // Log the resulting string writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); log.info(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(request, response); }
From source file:org.zilverline.web.RequestDumperFilter.java
/** * Time the processing that is performed by all subsequent filters in the current filter stack, including the ultimately invoked * servlet./* w ww .java 2 s.c om*/ * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } log.debug("Request Received at " + (new Timestamp(System.currentTimeMillis()))); log.debug(" characterEncoding=" + request.getCharacterEncoding()); log.debug(" contentLength=" + request.getContentLength()); log.debug(" contentType=" + request.getContentType()); log.debug(" locale=" + request.getLocale()); Enumeration locales = request.getLocales(); StringBuffer localesBuffer = new StringBuffer(" locales="); boolean first = true; while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); if (first) { first = false; } else { localesBuffer.append(", "); } localesBuffer.append(locale.toString()); } log.debug(localesBuffer); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); StringBuffer paramsBuffer = new StringBuffer(); paramsBuffer.append(" parameter=" + name + "="); String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { paramsBuffer.append(", "); } paramsBuffer.append(values[i]); } log.debug(paramsBuffer); } log.debug(" protocol=" + request.getProtocol()); log.debug(" remoteAddr=" + request.getRemoteAddr()); log.debug(" remoteHost=" + request.getRemoteHost()); log.debug(" scheme=" + request.getScheme()); log.debug(" serverName=" + request.getServerName()); log.debug(" serverPort=" + request.getServerPort()); log.debug(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { log.debug("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; log.debug(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { log.debug(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } names = hrequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = hrequest.getHeader(name); log.debug(" header=" + name + "=" + value); } log.debug(" method=" + hrequest.getMethod()); log.debug(" pathInfo=" + hrequest.getPathInfo()); log.debug(" queryString=" + hrequest.getQueryString()); log.debug(" remoteUser=" + hrequest.getRemoteUser()); log.debug("requestedSessionId=" + hrequest.getRequestedSessionId()); log.debug(" requestURI=" + hrequest.getRequestURI()); log.debug(" servletPath=" + hrequest.getServletPath()); } log.debug("============================================="); // Pass control on to the next filter chain.doFilter(request, response); }
From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java
/** {@inheritDoc} */ @SuppressWarnings(value = "unchecked") public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (this.config == null) { return;//from www.java 2 s . c om } // Just pass through to next filter if we're not at TRACE level if (!logger.isTraceEnabled()) { chain.doFilter(request, response); return; } // Create a variable to hold the (possibly different) request // passed to downstream filters ServletRequest downstreamRequest = request; // Render the generic servlet request properties final StringWriter sw = new StringWriter(); final PrintWriter writer = new PrintWriter(sw); writer.println("Dumping request..."); writer.println("-----------------------------------------------------"); writer.println("REQUEST received " + Calendar.getInstance().getTime()); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); final Enumeration<Locale> locales = request.getLocales(); for (int i = 0; locales.hasMoreElements(); i++) { if (i > 0) { writer.print(", "); } writer.print(locales.nextElement()); } writer.println(); final Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { final String name = paramNames.nextElement(); writer.print(" parameter=" + name + "="); final String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { writer.print(", "); } writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { final HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } final Enumeration<String> headerNames = hrequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); // Create a wrapped request that contains the request body // and that we will pass to downstream filters final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest); downstreamRequest = wrappedRequest; writer.println(wrappedRequest.getRequestBodyAsString()); } writer.println("-----------------------------------------------------"); // Log the resulting string writer.flush(); logger.trace(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(downstreamRequest, response); }
From source file:ORG.oclc.os.ipUseThrottleFilter.ipUseThrottleFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String longAddr = null, shortAddr, s, transactionKey = null; int count;// ww w .j a va 2 s. c o m boolean ignorable = false; synchronized (simultaneousRequestsByShortIPAddr) { if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) { log.error("This system has exceeded the maxTotalSimultaneousRequests limit of " + maxTotalSimultaneousRequests); log.error(simultaneousRequestsByShortIPAddr); for (String str : simultaneousRequests) log.error(str); ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body><h1>Service Temporarily Unavailable</h1>"); writer.println( "The system is experiencing a severe load and is temporarily unable to accept new requests"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } if (addressInHeader != null) { @SuppressWarnings("unchecked") Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader); while (addrs.hasMoreElements()) { longAddr = addrs.nextElement(); if (longAddr == null) { if (++addressInHeaderErrorCount < 10) log.error("Expected a " + addressInHeader + " header but got null"); continue; } if (longAddr.lastIndexOf('.') >= 0) break; } } if (longAddr == null) longAddr = request.getRemoteAddr(); int i = longAddr.lastIndexOf('.'); if (i < 0) { log.error("bogus IP address: '" + longAddr + "'"); longAddr = "0.0.0.0"; } shortAddr = longAddr.substring(0, i); // trim off 4th number group // that lets us spot requests from clusters s = equivalentAddresses.get(shortAddr); // map one short addr to another? if (s != null) shortAddr = s; if (ignorableAddresses.contains(shortAddr)) { ignorable = true; } else { Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr); if (icount != null) count = icount; else count = 0; int maxSimultaneousRequests = (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4; if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1; if (count >= maxSimultaneousRequests) { log.error("IP addr " + shortAddr + ".* has exceeded " + maxSimultaneousRequests + " simultaneous requests!"); log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests); log.error("totalSimultaneousRequests=" + totalSimultaneousRequests); for (String str : simultaneousRequests) log.error(str); // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); // someday ((HttpServletResponse) response).setStatus(429); // too many requests response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println( "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>"); writer.println("You have exceeded the maximum simultaneous request value of " + maxSimultaneousRequests); writer.println("<p>This message and your IP address have been logged and reported</p>"); if (contactInfo != null) writer.println("<p>Contact " + contactInfo + " for more information</p>"); writer.println("</body></html>"); writer.close(); return; } simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1); icount = totalRequests.get(shortAddr); if (icount != null) count = icount; else count = 0; totalRequests.put(shortAddr, count + 1); totalSimultaneousRequests++; transactionKey = new StringBuilder((new Date(System.currentTimeMillis())).toString()).append('|') .append(shortAddr).append('|').append(((HttpServletRequest) request).getQueryString()) .toString(); simultaneousRequests.add(transactionKey); } } try { HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response); chain.doFilter(request, wrapper); } finally { if (!ignorable) synchronized (simultaneousRequestsByShortIPAddr) { totalSimultaneousRequests--; simultaneousRequests.remove(transactionKey); count = simultaneousRequestsByShortIPAddr.get(shortAddr); if (count == 1) // prune them from the table simultaneousRequestsByShortIPAddr.remove(shortAddr); else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1); } } Calendar c = new GregorianCalendar(); int hour = c.get(Calendar.HOUR_OF_DAY); if (hour == 0 && nextReportingHour == 24) { // new day! // you could reset your daily limits table here nextReportingHour = 0; } if (hour >= nextReportingHour) { // generate the hourly report // you could reset your hourly limits table here nextReportingHour = hour + 1; if (log.isInfoEnabled()) { HashMap<String, Integer> map = new LinkedHashMap<String, Integer>(); List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet()); List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values()); TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues); Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]); int size = sortedArray.length; for (int i = 0; i < size; i++) map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]); Iterator<String> it = map.keySet().iterator(); String key; StringBuilder sb = new StringBuilder("Top 10 users in the last hour"); for (int i = 0; i < 10 && it.hasNext(); i++) { key = it.next(); sb.append("\n ").append(key).append(" : ").append(map.get(key)); } log.info(sb); } totalRequests.clear(); } }
From source file:org.apache.nifi.web.security.authorization.NodeAuthorizedUserFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; // get the proxied user's authorities final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS); // check if the request has the necessary header information and this instance is configured as a node if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) { // get the flow controller from the Spring context final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); final FlowController flowController = ctx.getBean("flowController", FlowController.class); // check that we are connected to the cluster if (flowController.getNodeId() != null) { try { // get the DN from the cert in the request final X509Certificate certificate = certificateExtractor .extractClientCertificate((HttpServletRequest) request); if (certificate != null) { // extract the principal from the certificate final Object certificatePrincipal = principalExtractor.extractPrincipal(certificate); final String dn = certificatePrincipal.toString(); // only consider the pre-authorized user when the request came from the NCM according to the DN in the certificate final String clusterManagerDN = flowController.getClusterManagerDN(); if (clusterManagerDN != null && clusterManagerDN.equals(dn)) { // deserialize hex encoded object final Serializable userDetailsObj = WebUtils .deserializeHexToObject(hexEncodedUserDetails); // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain if (userDetailsObj instanceof NiFiUserDetails) { final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj; final NiFiUser user = userDetails.getNiFiUser(); // log the request attempt - response details will be logged later logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getDn(), httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString(), request.getRemoteAddr())); // we do not create the authentication token with the X509 certificate because the certificate is from the sending system, not the proxied user final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( userDetails, null, userDetails.getAuthorities()); token.setDetails(authenticationDetailsSource.buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(token); }/*w w w . j av a2s . c o m*/ } } } catch (final ClassNotFoundException cnfe) { LOGGER.warn( "Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe); } } } chain.doFilter(request, response); }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;//from w w w .j a va2 s. c om ExtendedHttpMethod method; HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) method = new ExtendedGetMethod(); else method = new ExtendedPostMethod(); method.setDecompress(false); // for this create ui server and port, properties. JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getServerName()); capturedData.setRequestMethod(httpRequest.getMethod()); capturedData.setRequestHeader(httpRequest); capturedData.setHttpRequestParameters(httpRequest); capturedData.setTargetURL(httpRequest.getRequestURL().toString()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // check connection header String connectionHeader = httpRequest.getHeader("Connection"); if (connectionHeader != null) { connectionHeader = connectionHeader.toLowerCase(); if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0) connectionHeader = null; } // copy headers boolean xForwardedFor = false; @SuppressWarnings("unused") long contentLength = -1; Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if (dontProxyHeaders.contains(lhdr)) continue; if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) contentLength = request.getContentLength(); Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { method.setRequestHeader(lhdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers method.setRequestHeader("Via", "SoapUI Monitor"); if (!xForwardedFor) method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr()); if (method instanceof ExtendedPostMethod) ((ExtendedPostMethod) method) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); StringBuffer url = new StringBuffer("http://"); url.append(httpRequest.getServerName()); if (httpRequest.getServerPort() != 80) url.append(":" + httpRequest.getServerPort()); if (httpRequest.getServletPath() != null) { url.append(httpRequest.getServletPath()); method.setPath(httpRequest.getServletPath()); if (httpRequest.getQueryString() != null) { url.append("?" + httpRequest.getQueryString()); method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString()); } } hostConfiguration.setHost(new URI(url.toString(), true)); // SoapUI.log("PROXY to:" + url); monitor.fireBeforeProxy(request, response, method, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method); } // wait for transaction to end and store it. capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(method.getResponseBody()); capturedData.setResponseHeader(method); capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody())); capturedData.setResponseContent(new String(method.getDecompressedResponseBody())); monitor.fireAfterProxy(request, response, method, capturedData); if (!response.isCommitted()) { StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // capturedData = null; // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); } synchronized (this) { if (checkContentType(method)) { monitor.addMessageExchange(capturedData); } } }
From source file:org.apache.nifi.web.security.node.NodeAuthorizedUserFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; // get the proxied user's authorities final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS); // check if the request has the necessary header information and this instance is configured as a node if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) { // get the flow controller from the Spring context final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); final FlowController flowController = ctx.getBean("flowController", FlowController.class); // check that we are connected to the cluster if (flowController.getNodeId() != null) { try { // attempt to extract the client certificate final X509Certificate[] certificate = certificateExtractor .extractClientCertificate(httpServletRequest); if (certificate != null) { // authenticate the certificate final AuthenticationResponse authenticationResponse = certificateIdentityProvider .authenticate(certificate); // only consider the pre-authorized user when the request came directly from the NCM according to the DN in the certificate final String clusterManagerIdentity = flowController.getClusterManagerDN(); if (clusterManagerIdentity != null && clusterManagerIdentity.equals(authenticationResponse.getIdentity())) { // deserialize hex encoded object final Serializable userDetailsObj = WebUtils .deserializeHexToObject(hexEncodedUserDetails); // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain if (userDetailsObj instanceof NiFiUserDetails) { final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj; final NiFiUser user = userDetails.getNiFiUser(); // log the request attempt - response details will be logged later logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", user.getIdentity(), httpServletRequest.getMethod(), httpServletRequest.getRequestURL().toString(), request.getRemoteAddr())); // create the authorized nifi token final NiFiAuthorizationToken token = new NiFiAuthorizationToken(userDetails); SecurityContextHolder.getContext().setAuthentication(token); }//from w w w. ja va2s . co m } } } catch (final ClassNotFoundException cnfe) { LOGGER.warn( "Classpath issue detected because failed to deserialize authorized user in request header due to: " + cnfe, cnfe); } catch (final IllegalArgumentException iae) { // unable to authenticate a serialized user from the incoming request } } } chain.doFilter(request, response); }
From source file:org.alfresco.repo.webdav.auth.HTTPRequestAuthenticationFilter.java
/** * Run the authentication filter//from www . jav a 2s .co m * * @param req * ServletRequest * @param resp * ServletResponse * @param chain * FilterChain * @exception ServletException * @exception IOException */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // Assume it's an HTTP request final HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the user details object from the session SessionUser user = (SessionUser) httpReq.getSession().getAttribute(AUTHENTICATION_USER); if (user == null) { // Check for the auth header String authHdr = httpReq.getHeader(httpServletRequestAuthHeaderName); if (logger.isDebugEnabled()) { if (authHdr == null) { logger.debug("Header not found: " + httpServletRequestAuthHeaderName); } else { logger.debug("Header is <" + authHdr + ">"); } } // Throw an error if we have an unknown authentication if ((authHdr != null) && (authHdr.length() > 0)) { // Get the user final String userName; if (m_authPattern != null) { Matcher matcher = m_authPattern.matcher(authHdr); if (matcher.matches()) { userName = matcher.group(); if ((userName == null) || (userName.length() < 1)) { if (logger.isDebugEnabled()) { logger.debug("Extracted null or empty user name from pattern " + m_authPatternString + " against " + authHdr); } reject(httpReq, httpResp); return; } } else { if (logger.isDebugEnabled()) { logger.debug("no pattern match for " + m_authPatternString + " against " + authHdr); } reject(httpReq, httpResp); return; } } else { userName = authHdr; } if (logger.isDebugEnabled()) { logger.debug("User = " + userName); } // Get the authorization header user = transactionService.getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<SessionUser>() { public SessionUser execute() throws Throwable { try { // Authenticate the user m_authComponent.clearCurrentSecurityContext(); m_authComponent.setCurrentUser(userName); return createUserEnvironment(httpReq.getSession(), userName, authenticationService.getCurrentTicket(), true); } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed", ex); } return null; // Perhaps auto-creation/import is disabled } } }); } else { // Check if the request includes an authentication ticket String ticket = req.getParameter(ARG_TICKET); if (ticket != null && ticket.length() > 0) { // Debug if (logger.isDebugEnabled()) logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket); try { // Validate the ticket authenticationService.validate(ticket); // Need to create the User instance if not already available user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), ticket, true); } catch (AuthenticationException authErr) { // Clear the user object to signal authentication failure if (logger.isDebugEnabled()) { logger.debug("Failed", authErr); } user = null; } } } // Check if the user is authenticated, if not then prompt again if (user == null) { // No user/ticket, force the client to prompt for logon details reject(httpReq, httpResp); return; } } // Chain other filters chain.doFilter(req, resp); }
From source file:org.alfresco.repo.webdav.auth.AuthenticationFilter.java
/** * Run the authentication filter/* www .ja va 2s .com*/ * * @param context ServletContext * @param req ServletRequest * @param resp ServletResponse * @param chain FilterChain * @exception ServletException * @exception IOException */ public void doFilter(ServletContext context, ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) logger.debug("Entering AuthenticationFilter."); // Assume it's an HTTP request HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the user details object from the session SessionUser user = getSessionUser(context, httpReq, httpResp, false); if (user == null) { if (logger.isDebugEnabled()) logger.debug("There is no user in the session."); // Get the authorization header String authHdr = httpReq.getHeader("Authorization"); if (authHdr != null && authHdr.length() > 5 && authHdr.substring(0, 5).equalsIgnoreCase("BASIC")) { if (logger.isDebugEnabled()) logger.debug("Basic authentication details present in the header."); byte[] encodedString = Base64.decodeBase64(authHdr.substring(5).getBytes()); // ALF-13621: Due to browser inconsistencies we have to try a fallback path of encodings Set<String> attemptedAuths = new HashSet<String>(ENCODINGS.length * 2); for (String encoding : ENCODINGS) { CharsetDecoder decoder = Charset.forName(encoding).newDecoder() .onMalformedInput(CodingErrorAction.REPORT); try { // Attempt to decode using this charset String basicAuth = decoder.decode(ByteBuffer.wrap(encodedString)).toString(); // It decoded OK but we may already have tried this string. if (!attemptedAuths.add(basicAuth)) { // Already tried - no need to try again continue; } String username = null; String password = null; // Split the username and password int pos = basicAuth.indexOf(":"); if (pos != -1) { username = basicAuth.substring(0, pos); password = basicAuth.substring(pos + 1); } else { username = basicAuth; password = ""; } // Go to the repo and authenticate Authorization auth = new Authorization(username, password); if (auth.isTicket()) { authenticationService.validate(auth.getTicket()); } else { authenticationService.authenticate(username, password.toCharArray()); authenticationListener.userAuthenticated(new BasicAuthCredentials(username, password)); } user = createUserEnvironment(httpReq.getSession(), authenticationService.getCurrentUserName(), authenticationService.getCurrentTicket(), false); // Success so break out break; } catch (CharacterCodingException e) { if (logger.isDebugEnabled()) logger.debug("Didn't decode using " + decoder.getClass().getName(), e); } catch (AuthenticationException ex) { if (logger.isDebugEnabled()) logger.debug("Authentication error ", ex); } catch (NoSuchPersonException e) { if (logger.isDebugEnabled()) logger.debug("There is no such person error ", e); } } } else { // Check if the request includes an authentication ticket String ticket = req.getParameter(ARG_TICKET); if (ticket != null && ticket.length() > 0) { // PowerPoint bug fix if (ticket.endsWith(PPT_EXTN)) { ticket = ticket.substring(0, ticket.length() - PPT_EXTN.length()); } // Debug if (logger.isDebugEnabled()) logger.debug("Logon via ticket from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":" + req.getRemotePort() + ")" + " ticket=" + ticket); // Validate the ticket authenticationService.validate(ticket); authenticationListener.userAuthenticated(new TicketCredentials(ticket)); // Need to create the User instance if not already available String currentUsername = authenticationService.getCurrentUserName(); user = createUserEnvironment(httpReq.getSession(), currentUsername, ticket, false); } } // Check if the user is authenticated, if not then prompt again if (user == null) { if (logger.isDebugEnabled()) logger.debug("No user/ticket, force the client to prompt for logon details."); httpResp.setHeader("WWW-Authenticate", "BASIC realm=\"Alfresco DAV Server\""); httpResp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResp.flushBuffer(); return; } } else { authenticationListener.userAuthenticated(new TicketCredentials(user.getTicket())); } // Chain other filters chain.doFilter(req, resp); }