具有基本身份验证的简单jax-ws-webservice



我有一个简单的web服务WSDL。我使用wimport生成了java包装器。我已经在一个类"MyService"中实现了生成的接口。然后我发布这个带有Java6内置特性的web服务:

<>之前MyService = new MyService();Endpoint Endpoint =端点。发布(" http://localhost: 80/servicetest/服务/MyServiceINSoap",myService);之前

当我让这段代码运行时,一切都很完美——我可以用soapclient连接到服务,并且可以执行这些方法。

现在我希望javavm的内置web服务器使用基本身份验证-因此客户端必须提供用户id和密码。我该如何做到这一点?这可能吗?或者我是否需要一个应用程序服务器(tomcat、jboss等等)?

我已经搜索了一段时间,但只找到了托管在应用服务器上的webservice解决方案。

提前感谢!

erwrock

当我找到你的答案时,我很放心,因为我搜索了几个小时的解决方案。但是当我试图跟随你的链接时,我注意到这个页面不再可用了。幸运的是,我在Wayback Machine (https://archive.org/web/)的帮助下找到了旧版本。尽管这篇文章很棒,但我在获取基本授权以在客户端工作时遇到了一些问题。最后,我在java.net.Authenticator的帮助下使其工作。以下是我希望对其他人有用的代码片段。

服务器:

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()));
    }
}

找到解决方案:

https://today.java.net/pub/a/today/2007/07/03/jax-ws-web-services-without-ee-containers.html

经过几个小时的反复试验,终于在谷歌上找到了正确的搜索词:)

最新更新