JAX-WS:SOAP:仅使用JRE实现服务器Basic Authentification

时间:2017-02-06 17:41:37

标签: soap jax-ws basic-authentication

我已经使用Java 8运行时实现了JAX-WS。 现在我需要在客户端和服务器端添加基本身份验证支持:

  1. 我知道如何手动添加'授权:基本...'客户端的标头,但我希望客户端在收到来自服务器的401响应时添加它;
  2. 我不知道如何让服务器检查此标头值,如果缺少此标头或未通过凭据检查,则返回401响应;
  3. 我只需要基于JRE的实现(没有Tomcat,Weblogic,Glassfish等)。

1 个答案:

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

}