Search in sources :

Example 1 with BasicAuthenticator

use of com.sun.net.httpserver.BasicAuthenticator in project jetty.project by eclipse.

the class TestSPIServer method main.

public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    HttpServer server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host, port), 10);
    server.start();
    final HttpContext httpContext = server.createContext("/", new HttpHandler() {

        public void handle(HttpExchange exchange) throws IOException {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, 0);
            OutputStream responseBody = exchange.getResponseBody();
            Headers requestHeaders = exchange.getRequestHeaders();
            Set<String> keySet = requestHeaders.keySet();
            Iterator<String> iter = keySet.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                List values = requestHeaders.get(key);
                String s = key + " = " + values.toString() + "\n";
                responseBody.write(s.getBytes());
            }
            responseBody.close();
        }
    });
    httpContext.setAuthenticator(new BasicAuthenticator("Test") {

        @Override
        public boolean checkCredentials(String username, String password) {
            if ("username".equals(username) && password.equals("password"))
                return true;
            return false;
        }
    });
    Thread.sleep(10000000);
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) HttpContext(com.sun.net.httpserver.HttpContext) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) HttpServer(com.sun.net.httpserver.HttpServer) Iterator(java.util.Iterator) List(java.util.List)

Example 2 with BasicAuthenticator

use of com.sun.net.httpserver.BasicAuthenticator in project jdk8u_jdk by JetBrains.

the class BasicLongCredentials method main.

public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);
        BasicAuthenticator a = new BasicAuthenticator(REALM) {

            public boolean checkCredentials(String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();
        Authenticator.setDefault(new MyAuthenticator());
        URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/test/");
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read() != -1) {
            c++;
        }
        if (c != 0) {
            throw new RuntimeException("Test failed c = " + c);
        }
        if (error) {
            throw new RuntimeException("Test failed: error");
        }
        System.out.println("OK");
    } finally {
        server.stop(0);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) HttpServer(com.sun.net.httpserver.HttpServer) HttpContext(com.sun.net.httpserver.HttpContext) HttpHandler(com.sun.net.httpserver.HttpHandler) URL(java.net.URL)

Example 3 with BasicAuthenticator

use of com.sun.net.httpserver.BasicAuthenticator in project NoraUi by NoraUi.

the class TestServer method start.

public void start() {
    try {
        server = HttpServer.create(new InetSocketAddress(8000), 0);
    } catch (final Exception e) {
        Assert.fail("Exception thrown: " + e.getMessage());
    }
    server.createContext("/unprotected", new TestHttpHandler());
    final HttpContext protectedContext = server.createContext("/protected", new TestHttpHandler());
    protectedContext.setAuthenticator(new BasicAuthenticator("get") {

        @Override
        public boolean checkCredentials(String user, String pwd) {
            return user.equals("admin") && pwd.equals("admin");
        }
    });
    server.setExecutor(null);
    server.start();
}
Also used : BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) InetSocketAddress(java.net.InetSocketAddress) HttpContext(com.sun.net.httpserver.HttpContext) IOException(java.io.IOException) TechnicalException(com.github.noraui.exception.TechnicalException) FailureException(com.github.noraui.exception.FailureException)

Example 4 with BasicAuthenticator

use of com.sun.net.httpserver.BasicAuthenticator in project ant-ivy by apache.

the class TestHelper method createBasicAuthHttpServerBackedRepo.

/**
 * Creates a HTTP server, backed by a local file system, which can be used as a repository to
 * serve Ivy module descriptors and artifacts. The context within the server will be backed by
 * {@code BASIC} authentication mechanism with {@code realm} as the realm and
 * {@code validCredentials} as the credentials that the server will recognize. The server will
 * allow access to resources, only if the credentials that are provided by the request, belong
 * to these credentials.
 * <p>
 * NOTE: This is supposed to be used only in test cases and only a limited functionality is
 * added in the handler(s) backing the server
 *
 * @param serverAddress           The address to which the server will be bound
 * @param webAppContext           The context root of the application which will be handling
 *                                the requests to the server
 * @param localFilesystemRepoRoot The path to the root directory containing the module
 *                                descriptors and artifacts
 * @param realm                   The realm to use for the {@code BASIC} auth mechanism
 * @param validCredentials        A {@link Map} of valid credentials, the key being the user
 *                                name and the value being the password, that the server will
 *                                use during the authentication process of the incoming requests
 * @return AutoCloseable
 * @throws IOException if something goes wrong
 */
public static AutoCloseable createBasicAuthHttpServerBackedRepo(final InetSocketAddress serverAddress, final String webAppContext, final Path localFilesystemRepoRoot, final String realm, final Map<String, String> validCredentials) throws IOException {
    final LocalFileRepoOverHttp handler = new LocalFileRepoOverHttp(webAppContext, localFilesystemRepoRoot);
    final HttpServer server = HttpServer.create(serverAddress, -1);
    // setup the handler
    final HttpContext context = server.createContext(webAppContext, handler);
    // setup basic auth on this context
    final com.sun.net.httpserver.Authenticator authenticator = new BasicAuthenticator(realm) {

        @Override
        public boolean checkCredentials(final String user, final String pass) {
            if (validCredentials == null || !validCredentials.containsKey(user)) {
                return false;
            }
            final String expectedPass = validCredentials.get(user);
            return expectedPass != null && expectedPass.equals(pass);
        }
    };
    context.setAuthenticator(authenticator);
    // setup a auth filter backed by the authenticator
    context.getFilters().add(new AuthFilter(authenticator));
    // start the server
    server.start();
    return new AutoCloseable() {

        @Override
        public void close() throws Exception {
            final int delaySeconds = 0;
            server.stop(delaySeconds);
        }
    };
}
Also used : BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) HttpServer(com.sun.net.httpserver.HttpServer) HttpContext(com.sun.net.httpserver.HttpContext)

Example 5 with BasicAuthenticator

use of com.sun.net.httpserver.BasicAuthenticator in project jdk8u_jdk by JetBrains.

the class Deadlock method main.

public static void main(String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress(0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("foobar@test.realm") {

        @Override
        public boolean checkCredentials(String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };
    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start();
    java.net.Authenticator.setDefault(new MyAuthenticator());
    System.out.print("Deadlock: ");
    for (int i = 0; i < 2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }
    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");
}
Also used : BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) HttpContext(com.sun.net.httpserver.HttpContext) ExecutorService(java.util.concurrent.ExecutorService) HttpHandler(com.sun.net.httpserver.HttpHandler)

Aggregations

BasicAuthenticator (com.sun.net.httpserver.BasicAuthenticator)5 HttpContext (com.sun.net.httpserver.HttpContext)5 HttpServer (com.sun.net.httpserver.HttpServer)4 InetSocketAddress (java.net.InetSocketAddress)4 HttpHandler (com.sun.net.httpserver.HttpHandler)3 IOException (java.io.IOException)2 FailureException (com.github.noraui.exception.FailureException)1 TechnicalException (com.github.noraui.exception.TechnicalException)1 Headers (com.sun.net.httpserver.Headers)1 HttpExchange (com.sun.net.httpserver.HttpExchange)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Set (java.util.Set)1 ExecutorService (java.util.concurrent.ExecutorService)1