我已经使用Java 8运行时实现了JAX-WS。 现在我需要在客户端和服务器端添加基本身份验证支持:
答案 0 :(得分:1)
虽然您可能已经解决了问题,但我想提供一个示例实现,如果其他人对它有一些用处。
服务器:
javax.xml.ws.Endpoint serverEndpoint = Endpoint.create(new MyService());
com.sun.net.httpserver.HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
com.sun.net.httpserver.HttpContext httpContext = server.createContext("/myservice");
server.start();
AuthenticatorServer authenticatorServer = new AuthenticatorServer("myRealm", "myName", "myPwd");
httpContext.setAuthenticator(authenticatorServer);
serverEndpoint.publish(httpContext);
AuthenticatorServer是:
private static class AuthenticatorServer extends com.sun.net.httpserver.BasicAuthenticator {
private final String user;
private final String pwd;
public AuthenticatorServer(String realm, String user, String pwd) {
super(realm);
this.user = user;
this.pwd = pwd;
}
@Override
public boolean checkCredentials(String userNameInput, String passwordInput) {
return StringUtils.equals(user, userNameInput) && StringUtils.equals(pwd, passwordInput);
}
}
在客户端:
AuthenticatorClient authenticatorClient = new AuthenticatorClient("myName", "myPwd");
Authenticator.setDefault(authenticatorClient);
javax.xml.namespace.QName qName = new QName(namespaceURI, WS_SERVICE_NAME);
java.net.URL wsdlAddress = new URL(namespaceURI + WS_SERVICE_NAME + "?wsdl");
MyService service =(Service.create(wsdlAddress, qName)).getPort(MyService.class);
AuthenticatorClient在哪里:
private static class AuthenticatorClient extends java.net.Authenticator {
private final String user;
private final String pwd;
public AuthenticatorClient(String user, String pwd) {
this.user = user;
this.pwd = pwd;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pwd == null ? null : pwd.toCharArray()));
}
}