org.littleshoot.proxy.ProxyAuthenticator Java Examples

The following examples show how to use org.littleshoot.proxy.ProxyAuthenticator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestHttpClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static void startProxyServerWithAuth() throws IOException {
    int proxyServerPort;
    try (final ServerSocket serverSocket = new ServerSocket(0)) {
        proxyServerPort = serverSocket.getLocalPort();
    }
    proxyServerWithAuth = DefaultHttpProxyServer.bootstrap()
            .withPort(proxyServerPort)
            .withAllowLocalOnly(true)
            .withProxyAuthenticator(new ProxyAuthenticator() {
                @Override
                public boolean authenticate(String userName, String password) {
                    return PROXY_USER.equals(userName) && PROXY_PASSWORD.equals(password);
                }

                @Override
                public String getRealm() {
                    return "NiFi Unit Test";
                }
            })
            // Use less threads to mitigate Gateway Timeout (504) with proxy test
            .withThreadPoolConfiguration(new ThreadPoolConfiguration()
                    .withAcceptorThreads(2)
                    .withClientToProxyWorkerThreads(4)
                    .withProxyToServerWorkerThreads(4))
            .start();
}
 
Example #2
Source File: SalesforceProxyTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupProxy() {
    ProxyAuthenticator auth = new ProxyAuthenticator() {

        @Override
        public boolean authenticate(String username, String password) {
            return proxyUsername.equals(username) && proxyPassword.equals(password);
        }

        @Override
        public String getRealm() {
            return null;
        }

    };
    server = DefaultHttpProxyServer.bootstrap().withPort(proxyPort).withProxyAuthenticator(auth).start();

    setProxySettingForClient();
}
 
Example #3
Source File: HTTPSProxyAuthConduitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startProxy() {
    System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
    proxy = DefaultHttpProxyServer.bootstrap()
        .withPort(PROXY_PORT)
        .withProxyAuthenticator(new ProxyAuthenticator() {
            @Override
            public boolean authenticate(String userName, String password) {
                return "password".equals(password) && "CXF".equals(userName);
            }
            @Override
            public String getRealm() {
                return null;
            }
        })
        .plusActivityTracker(requestFilter)
        .start();
}
 
Example #4
Source File: HTTPProxyAuthConduitTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startProxy() {
    proxy = DefaultHttpProxyServer.bootstrap()
        .withPort(PROXY_PORT)
        .withProxyAuthenticator(new ProxyAuthenticator() {
            @Override
            public boolean authenticate(String userName, String password) {
                return "password".equals(password) && "CXF".equals(userName);
            }
            @Override
            public String getRealm() {
                return null;
            }
        })
        .plusActivityTracker(requestFilter)
        .start();
}
 
Example #5
Source File: TestHttpClient.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void startProxyServerWithAuth() throws IOException {
    int proxyServerPort;
    try (final ServerSocket serverSocket = new ServerSocket(0)) {
        proxyServerPort = serverSocket.getLocalPort();
    }
    proxyServerWithAuth = DefaultHttpProxyServer.bootstrap()
            .withPort(proxyServerPort)
            .withAllowLocalOnly(true)
            .withProxyAuthenticator(new ProxyAuthenticator() {
                @Override
                public boolean authenticate(String userName, String password) {
                    return PROXY_USER.equals(userName) && PROXY_PASSWORD.equals(password);
                }

                @Override
                public String getRealm() {
                    return "NiFi Unit Test";
                }
            })
            // Use less threads to mitigate Gateway Timeout (504) with proxy test
            .withThreadPoolConfiguration(new ThreadPoolConfiguration()
                    .withAcceptorThreads(2)
                    .withClientToProxyWorkerThreads(4)
                    .withProxyToServerWorkerThreads(4))
            .start();
}
 
Example #6
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpProxyServer start() {
	log.info("*** STARTED TEST PROXY SERVER ***");
	HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap().withPort(8089).withProxyAuthenticator(new ProxyAuthenticator() {
		@Override
		public boolean authenticate(String username, String password) {
			return username.equals("test") && password.equals("works");
		}

		@Override
		public String getRealm() {
			return null;
		}
	}).start();
	return proxyServer;
}
 
Example #7
Source File: ProxyServerUtil.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpProxyServer start() {
	log.info("*** STARTED TEST PROXY SERVER ***");
	HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap().withPort(8089).withProxyAuthenticator(new ProxyAuthenticator() {
		@Override
		public boolean authenticate(String username, String password) {
			return username.equals("test") && password.equals("works");
		}

		@Override
		public String getRealm() {
			return null;
		}
	}).start();
	return proxyServer;
}
 
Example #8
Source File: ProxyTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a proxy server counting requests
 * @param authenticating true if the proxy should require authentication
 * @throws Exception if an error occurred
 */
private void startProxy(boolean authenticating) throws Exception {
    proxyPort = findPort();
    
    HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer.bootstrap()
            .withPort(proxyPort)
            .withFiltersSource(new HttpFiltersSourceAdapter() {
                public HttpFilters filterRequest(HttpRequest originalRequest,
                        ChannelHandlerContext ctx) {
                   return new HttpFiltersAdapter(originalRequest) {
                      @Override
                      public void proxyToServerRequestSent() {
                          proxyCounter++;
                      }
                   };
                }
            });
    
    if (authenticating) {
        bootstrap = bootstrap.withProxyAuthenticator(new ProxyAuthenticator() {
            @Override
            public boolean authenticate(String userName, String password) {
                return PROXY_USERNAME.equals(userName) &&
                        PROXY_PASSWORD.equals(password);
            }

            @Override
            public String getRealm() {
                return "gradle-download-task";
            }
        });
    }
    
    proxy = bootstrap.start();
}
 
Example #9
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Checks whether the given HttpRequest requires authentication.
 * </p>
 * 
 * <p>
 * If the request contains credentials, these are checked.
 * </p>
 * 
 * <p>
 * If authentication is still required, either because no credentials were
 * provided or the credentials were wrong, this writes a 407 response to the
 * client.
 * </p>
 * 
 * @param request
 * @return
 */
private boolean authenticationRequired(HttpRequest request) {

    if (authenticated.get()) {
        return false;
    }

    final ProxyAuthenticator authenticator = proxyServer
            .getProxyAuthenticator();

    if (authenticator == null)
        return false;

    if (!request.headers().contains(HttpHeaders.Names.PROXY_AUTHORIZATION)) {
        writeAuthenticationRequired(authenticator.getRealm());
        return true;
    }

    List<String> values = request.headers().getAll(
            HttpHeaders.Names.PROXY_AUTHORIZATION);
    String fullValue = values.iterator().next();
    String value = StringUtils.substringAfter(fullValue, "Basic ").trim();

    byte[] decodedValue = BaseEncoding.base64().decode(value);

    String decodedString = new String(decodedValue, Charset.forName("UTF-8"));
    
    String userName = StringUtils.substringBefore(decodedString, ":");
    String password = StringUtils.substringAfter(decodedString, ":");
    if (!authenticator.authenticate(userName, password)) {
        writeAuthenticationRequired(authenticator.getRealm());
        return true;
    }

    LOG.debug("Got proxy authorization!");
    // We need to remove the header before sending the request on.
    String authentication = request.headers().get(
            HttpHeaders.Names.PROXY_AUTHORIZATION);
    LOG.debug(authentication);
    request.headers().remove(HttpHeaders.Names.PROXY_AUTHORIZATION);
    authenticated.set(true);
    return false;
}
 
Example #10
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new proxy server.
 *
 * @param serverGroup                 our ServerGroup for shared thread pools and such
 * @param transportProtocol           The protocol to use for data transport
 * @param requestedAddress            The address on which this server will listen
 * @param sslEngineSource             (optional) if specified, this Proxy will encrypt inbound
 *                                    connections from clients using an {@link SSLEngine} obtained
 *                                    from this {@link SslEngineSource}.
 * @param authenticateSslClients      Indicate whether or not to authenticate clients when using SSL
 * @param proxyAuthenticator          (optional) If specified, requests to the proxy will be
 *                                    authenticated using HTTP BASIC authentication per the provided
 *                                    {@link ProxyAuthenticator}
 * @param chainProxyManager           The proxy to send requests to if chaining proxies. Typically
 *                                    <code>null</code>.
 * @param mitmManager                 The {@link MitmManager} to use for man in the middle'ing
 *                                    CONNECT requests
 * @param filtersSource               Source for {@link HttpFilters}
 * @param transparent                 If true, this proxy will run as a transparent proxy. This will
 *                                    not modify the response, and will only modify the request to
 *                                    amend the URI if the target is the origin server (to comply
 *                                    with RFC 7230 section 5.3.1).
 * @param idleConnectionTimeout       The timeout (in seconds) for auto-closing idle connections.
 * @param activityTrackers            for tracking activity on this proxy
 * @param connectTimeout              number of milliseconds to wait to connect to the upstream
 *                                    server
 * @param serverResolver              the {@link HostResolver} to use for resolving server addresses
 * @param readThrottleBytesPerSecond  read throttle bandwidth
 * @param writeThrottleBytesPerSecond write throttle bandwidth
 * @param maxInitialLineLength
 * @param maxHeaderSize
 * @param maxChunkSize
 * @param allowRequestsToOriginServer when true, allow the proxy to handle requests that contain an origin-form URI, as defined in RFC 7230 5.3.1
 */
private DefaultHttpProxyServer(ServerGroup serverGroup,
                               TransportProtocol transportProtocol,
                               InetSocketAddress requestedAddress,
                               SslEngineSource sslEngineSource,
                               boolean authenticateSslClients,
                               ProxyAuthenticator proxyAuthenticator,
                               ChainedProxyManager chainProxyManager,
                               MitmManager mitmManager,
                               HttpFiltersSource filtersSource,
                               boolean transparent,
                               int idleConnectionTimeout,
                               Collection<ActivityTracker> activityTrackers,
                               int connectTimeout,
                               HostResolver serverResolver,
                               long readThrottleBytesPerSecond,
                               long writeThrottleBytesPerSecond,
                               InetSocketAddress localAddress,
                               String proxyAlias,
                               int maxInitialLineLength,
                               int maxHeaderSize,
                               int maxChunkSize,
                               boolean allowRequestsToOriginServer) {
    this.serverGroup = serverGroup;
    this.transportProtocol = transportProtocol;
    this.requestedAddress = requestedAddress;
    this.sslEngineSource = sslEngineSource;
    this.authenticateSslClients = authenticateSslClients;
    this.proxyAuthenticator = proxyAuthenticator;
    this.chainProxyManager = chainProxyManager;
    this.mitmManager = mitmManager;
    this.filtersSource = filtersSource;
    this.transparent = transparent;
    this.idleConnectionTimeout = idleConnectionTimeout;
    if (activityTrackers != null) {
        this.activityTrackers.addAll(activityTrackers);
    }
    this.connectTimeout = connectTimeout;
    this.serverResolver = serverResolver;

    if (writeThrottleBytesPerSecond > 0 || readThrottleBytesPerSecond > 0) {
        this.globalTrafficShapingHandler = createGlobalTrafficShapingHandler(transportProtocol, readThrottleBytesPerSecond, writeThrottleBytesPerSecond);
    } else {
        this.globalTrafficShapingHandler = null;
    }
    this.localAddress = localAddress;

    if (proxyAlias == null) {
        // attempt to resolve the name of the local machine. if it cannot be resolved, use the fallback name.
        String hostname = ProxyUtils.getHostName();
        if (hostname == null) {
            hostname = FALLBACK_PROXY_ALIAS;
        }
        this.proxyAlias = hostname;
    } else {
        this.proxyAlias = proxyAlias;
    }
    this.maxInitialLineLength = maxInitialLineLength;
    this.maxHeaderSize = maxHeaderSize;
    this.maxChunkSize = maxChunkSize;
    this.allowRequestsToOriginServer = allowRequestsToOriginServer;
}
 
Example #11
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
protected ProxyAuthenticator getProxyAuthenticator() {
    return proxyAuthenticator;
}
 
Example #12
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
private DefaultHttpProxyServerBootstrap(
        ServerGroup serverGroup,
        TransportProtocol transportProtocol,
        InetSocketAddress requestedAddress,
        SslEngineSource sslEngineSource,
        boolean authenticateSslClients,
        ProxyAuthenticator proxyAuthenticator,
        ChainedProxyManager chainProxyManager,
        MitmManager mitmManager,
        HttpFiltersSource filtersSource,
        boolean transparent, int idleConnectionTimeout,
        Collection<ActivityTracker> activityTrackers,
        int connectTimeout, HostResolver serverResolver,
        long readThrottleBytesPerSecond,
        long writeThrottleBytesPerSecond,
        InetSocketAddress localAddress,
        String proxyAlias,
        int maxInitialLineLength,
        int maxHeaderSize,
        int maxChunkSize,
        boolean allowRequestToOriginServer) {
    this.serverGroup = serverGroup;
    this.transportProtocol = transportProtocol;
    this.requestedAddress = requestedAddress;
    this.port = requestedAddress.getPort();
    this.sslEngineSource = sslEngineSource;
    this.authenticateSslClients = authenticateSslClients;
    this.proxyAuthenticator = proxyAuthenticator;
    this.chainProxyManager = chainProxyManager;
    this.mitmManager = mitmManager;
    this.filtersSource = filtersSource;
    this.transparent = transparent;
    this.idleConnectionTimeout = idleConnectionTimeout;
    if (activityTrackers != null) {
        this.activityTrackers.addAll(activityTrackers);
    }
    this.connectTimeout = connectTimeout;
    this.serverResolver = serverResolver;
    this.readThrottleBytesPerSecond = readThrottleBytesPerSecond;
    this.writeThrottleBytesPerSecond = writeThrottleBytesPerSecond;
    this.localAddress = localAddress;
    this.proxyAlias = proxyAlias;
    this.maxInitialLineLength = maxInitialLineLength;
    this.maxHeaderSize = maxHeaderSize;
    this.maxChunkSize = maxChunkSize;
    this.allowRequestToOriginServer = allowRequestToOriginServer;
}
 
Example #13
Source File: DefaultHttpProxyServer.java    From g4proxy with Apache License 2.0 4 votes vote down vote up
@Override
public HttpProxyServerBootstrap withProxyAuthenticator(
        ProxyAuthenticator proxyAuthenticator) {
    this.proxyAuthenticator = proxyAuthenticator;
    return this;
}
 
Example #14
Source File: HttpProxyTest.java    From java-cloudant with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a littleproxy instance that will proxy the requests. Applies appropriate configuration
 * options to the proxy based on the test parameters.
 *
 * @throws Exception
 */
@BeforeEach
public void setupAndStartProxy(final boolean okUsable,
                               final boolean useSecureProxy,
                               final boolean useHttpsServer,
                               final boolean useProxyAuth) throws Exception {

    HttpProxyServerBootstrap proxyBoostrap = DefaultHttpProxyServer.bootstrap()
            .withAllowLocalOnly(true) // only run on localhost
            .withAuthenticateSslClients(false); // we aren't checking client certs

    if (useProxyAuth) {
        // check the proxy user and password
        ProxyAuthenticator pa = new ProxyAuthenticator() {
            @Override
            public boolean authenticate(String userName, String password) {
                return (mockProxyUser.equals(userName) && mockProxyPass.equals(password));
            }

            @Override
            public String getRealm() {
                return null;
            }
        };
        proxyBoostrap.withProxyAuthenticator(pa);
    }

    if (useSecureProxy) {
        proxyBoostrap.withSslEngineSource(new SslEngineSource() {
            @Override
            public SSLEngine newSslEngine() {
                return MockWebServerResources.getSSLContext().createSSLEngine();
            }

            @Override
            public SSLEngine newSslEngine(String peerHost, int peerPort) {
                return MockWebServerResources.getSSLContext().createSSLEngine(peerHost,
                        peerPort);
            }
        });
    }

    // Start the proxy server
    proxy = proxyBoostrap.start();
}