Home > Java > Basic authentication with JAX-WS in Java SE

Basic authentication with JAX-WS in Java SE

With JAX-WS web services it is common to use preemptive basic authentication. It is also common to test the services stand-alone using the built-in support in Java SE. Unfortunately that makes it hard to test the authentication and no principal will be available on the server side. What to do?

It turns out that it is fairly easy to enable authentication after all. I found this example from 2007. In short the endpoint is published using Sun’s built-in web server.

This publishes the web service ExampleWebService on a random port with a hard-coded user and password:


HttpServer webServer = HttpServer.create(new InetSocketAddress(0), 1);
webServer.start();
HttpContext context = webServer.createContext("/");
context.setAuthenticator(new BasicAuthenticator("ExampleRealm") {
  public boolean checkCredentials(String username, String password) {
    return "testuser".equals(username) && "testpassword".equals(password);
  }
});
Endpoint endpoint = Endpoint.create(new ExampleWebService());
endpoint.publish(context);

Don’t forget to stop the web server after the test. Sun’s web server may not always be available in production, but it is most likely there in the unit test environment.

Advertisements
Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: