2017-02-06 42 views
0

我已經使用Java 8運行時實現了JAX-WS。 現在我需要在客戶端和服務器端添加基本的身份驗證支持:JAX-WS:SOAP:實現服務器僅使用JRE進行基本身份驗證

  1. 我知道如何手動添加的「授權:基本...」在客戶端頭,但我想在客戶端當它僅收到來自服務器的401響應時添加它;
  2. 我不知道如何使服務器檢查此標頭值並返回401響應如果此標題丟失或憑證檢查未通過;
  3. 我只需要基於JRE的實現(沒有Tomcat,Weblogic,Glassfish等)。

回答

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

} 
相關問題