今天把以前写的java6 web service Security的例子拿出来跑一跑,想整理一下写篇文章。结果发现代码不能跑了。
代码如下
--------------------------------------server--------------------------------------------------------
package
publish;
import
java.util.LinkedList;
import
java.util.List;
import
javax.xml.ws.Binding;
import
javax.xml.ws.Endpoint;
import
javax.xml.ws.handler.Handler;
import
security.SecurityHandler;
import
service.SecurityHello;
public
class
SecturityPublishApplication {
/**
*
@param
args
*/
public
static
void
main(String[] args) {
//
wsimport -keep
http://127.0.0.1
:8088/SecurityHello?wsdl
System.out.println(
"
准备启动服务
"
);
Endpoint endpoint
=
Endpoint.publish(
"
http://127.0.0.1:8088/SecurityHello
"
,
new
SecurityHello());
Binding binding
=
endpoint.getBinding();
List
<
Handler
>
handlerChain
=
new
LinkedList
<
Handler
>
();
handlerChain.add(
new
SecurityHandler());
binding.setHandlerChain(handlerChain);
System.out.println(
"
服务启动完毕
"
);
}
}
package
org.hermit.study.jdk.shello;
import
javax.jws.WebMethod;
import
javax.jws.WebParam;
import
javax.jws.WebResult;
import
javax.jws.WebService;
import
javax.jws.soap.SOAPBinding;
/**
* This class was generated by the JAXWS SI.
* JAX-WS RI 2.0_02-b08-fcs
* Generated source version: 2.0
*
*/
@WebService(name
=
"
SecurityHello
"
, targetNamespace
=
"
http://jdk.study.hermit.org/shello
"
)
@SOAPBinding(style
=
SOAPBinding.Style.RPC)
public
interface
SecurityHello {
/**
*
*
@param
arg0
*
@return
* returns java.lang.String
*/
@WebMethod
@WebResult(partName
=
"
return
"
)
public
String sayHello(
@WebParam(name
=
"
arg0
"
, partName
=
"
arg0
"
)
String arg0);
}
package
org.hermit.study.jdk.shello;
import
java.net.MalformedURLException;
import
java.net.URL;
import
javax.xml.namespace.QName;
import
javax.xml.ws.Service;
import
javax.xml.ws.WebEndpoint;
import
javax.xml.ws.WebServiceClient;
/**
* This class was generated by the JAXWS SI.
* JAX-WS RI 2.0_02-b08-fcs
* Generated source version: 2.0
*
*/
@WebServiceClient(name
=
"
SecurityHelloService
"
, targetNamespace
=
"
http://jdk.study.hermit.org/shello
"
, wsdlLocation
=
"
http://127.0.0.1:8088/SecurityHello?wsdl
"
)
public
class
SecurityHelloService
extends
Service
{
private
final
static
URL SECURITYHELLOSERVICE_WSDL_LOCATION;
static
{
URL url
=
null
;
try
{
url
=
new
URL(
"
http://127.0.0.1:8088/SecurityHello?wsdl
"
);
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
SECURITYHELLOSERVICE_WSDL_LOCATION
=
url;
}
public
SecurityHelloService(URL wsdlLocation, QName serviceName) {
super
(wsdlLocation, serviceName);
}
public
SecurityHelloService() {
super
(SECURITYHELLOSERVICE_WSDL_LOCATION,
new
QName(
"
http://jdk.study.hermit.org/shello
"
,
"
SecurityHelloService
"
));
}
/**
*
*
@return
* returns SecurityHello
*/
@WebEndpoint(name
=
"
SecurityHelloPort
"
)
public
SecurityHello getSecurityHelloPort() {
return
(SecurityHello)
super
.getPort(
new
QName(
"
http://jdk.study.hermit.org/shello
"
,
"
SecurityHelloPort
"
), SecurityHello.
class
);
}
}
user-pass-authenticate-server.xml
<!--
Copyright 2004 Sun Microsystems, Inc. All rights reserved.
SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
-->
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config" dumpMessages="true" >
<xwss:RequireUsernameToken passwordDigestRequired="true"/>
</xwss:SecurityConfiguration>
/*
* SecurityHandler.java
*
* Created on March 26, 2007, 12:58 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package security;
import java.io.File;
import java.io.FileInputStream;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import com.sun.xml.wss.ProcessingContext;
import com.sun.xml.wss.SubjectAccessor;
import com.sun.xml.wss.XWSSProcessor;
import com.sun.xml.wss.XWSSProcessorFactory;
import com.sun.xml.wss.XWSSecurityException;
/**
*
* Kumar Jayanti
*/
public class SecurityHandler implements SOAPHandler<SOAPMessageContext> {
XWSSProcessor sprocessor = null;
XWSSProcessor cprocessor = null;
public SecurityHandler() {
FileInputStream serverConfig = null;
try {
serverConfig = new FileInputStream(new File("./src/publish/user-pass-authenticate-server.xml"));
XWSSProcessorFactory factory = XWSSProcessorFactory.newInstance();
sprocessor = factory.createProcessorForSecurityConfiguration(serverConfig, new SecurityEnvironmentHandler("server"));
serverConfig.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public Set<QName> getHeaders() {
return null;
}
public boolean handleFault(SOAPMessageContext messageContext) {
return true;
}
public boolean handleMessage(SOAPMessageContext messageContext) {
secureServer(messageContext);
return true;
}
public void close(MessageContext messageContext) {
}
private void secureServer(SOAPMessageContext messageContext) {
Boolean outMessageIndicator = (Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
SOAPMessage message = messageContext.getMessage();
if (outMessageIndicator.booleanValue()) {
return;
} else {
try {
ProcessingContext context = sprocessor.createProcessingContext(message);
context.getExtraneousProperties().putAll(messageContext);
context.setSOAPMessage(message);
SOAPMessage verifiedMsg = sprocessor.verifyInboundMessage(context);
messageContext.setMessage(verifiedMsg);
} catch (XWSSecurityException ex) {
ex.printStackTrace();
throw new WebServiceException(ex);
} catch (Exception ex) {
ex.printStackTrace();
throw new WebServiceException(ex);
}
}
}
}
package security;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.xml.ws.BindingProvider;
import com.sun.xml.wss.impl.callback.PasswordCallback;
import com.sun.xml.wss.impl.callback.PasswordValidationCallback;
import com.sun.xml.wss.impl.callback.UsernameCallback;
public class SecurityEnvironmentHandler implements CallbackHandler {
private static final UnsupportedCallbackException unsupported = new UnsupportedCallbackException(null,
"Unsupported Callback Type Encountered");
public SecurityEnvironmentHandler(String arg) {
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof PasswordValidationCallback) {
PasswordValidationCallback cb = (PasswordValidationCallback) callbacks[i];
if (cb.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
cb.setValidator(new PlainTextPasswordValidator());
}
else if (cb.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest request = (PasswordValidationCallback.DigestPasswordRequest) cb
.getRequest();
String username = request.getUsername();
if ("hermit".equals(username)) {
request.setPassword("hermit");
cb.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
}
} else if (callbacks[i] instanceof UsernameCallback) {
UsernameCallback cb = (UsernameCallback) callbacks[i];
String username = (String) cb.getRuntimeProperties().get(BindingProvider.USERNAME_PROPERTY);
System.out.println("Got Username : " + username);
cb.setUsername(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback cb = (PasswordCallback) callbacks[i];
String password = (String) cb.getRuntimeProperties().get(BindingProvider.PASSWORD_PROPERTY);
System.out.println("Got Password : " + password);
cb.setPassword(password);
} else {
throw unsupported;
}
}
}
private class PlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
public boolean validate(PasswordValidationCallback.Request request) throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest = (PasswordValidationCallback.PlainTextPasswordRequest) request;
if ("hermit".equals(plainTextRequest.getUsername()) && "hermit".equals(plainTextRequest.getPassword())) {
return true;
}
return false;
}
}
}
-------------------------------------client---------------------------------------------------
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import org.hermit.study.jdk.shello.SecurityHandler;
import org.hermit.study.jdk.shello.SecurityHello;
import org.hermit.study.jdk.shello.SecurityHelloService;
public class TestSericutyHello {
public static void main(String[] args) {
try {
SecurityHelloService service = new SecurityHelloService();
SecurityHello port = service.getSecurityHelloPort();
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "hermit");
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "hermit");
List<Handler> chain = new ArrayList<Handler>();
chain.add(new SecurityHandler());
((BindingProvider) port).getBinding().setHandlerChain(chain);
String result = port.sayHello("Hermit");
System.out.println("Result = " + result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/*
* SecurityEnvironmentHandler.java
*
* Created on March 26, 2007, 1:17 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.hermit.study.jdk.shello;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import com.sun.xml.wss.impl.callback.PasswordCallback;
import com.sun.xml.wss.impl.callback.PasswordValidationCallback;
import com.sun.xml.wss.impl.callback.UsernameCallback;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.xml.ws.BindingProvider;
/**
*
* @author sk112103
*/
public class SecurityEnvironmentHandler implements CallbackHandler {
private static final UnsupportedCallbackException unsupported =
new UnsupportedCallbackException(null, "Unsupported Callback Type Encountered");
/** Creates a new instance of SecurityEnvironmentHandler */
public SecurityEnvironmentHandler(String arg) {
}
private String readLine() throws IOException {
return new BufferedReader
(new InputStreamReader(System.in)).readLine();
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i=0; i < callbacks.length; i++) {
if (callbacks[i] instanceof PasswordValidationCallback) {
PasswordValidationCallback cb = (PasswordValidationCallback) callbacks[i];
if (cb.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
cb.setValidator(new PlainTextPasswordValidator());
} else if (cb.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest request =
(PasswordValidationCallback.DigestPasswordRequest) cb.getRequest();
String username = request.getUsername();
if ("Ron".equals(username)) {
request.setPassword("noR");
cb.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
}
} else if (callbacks[i] instanceof UsernameCallback) {
UsernameCallback cb = (UsernameCallback)callbacks[i];
String username = (String)cb.getRuntimeProperties().get(BindingProvider.USERNAME_PROPERTY);
System.out.println("Got Username : " + username);
cb.setUsername(username);
} else if (callbacks[i] instanceof PasswordCallback) {
PasswordCallback cb = (PasswordCallback)callbacks[i];
String password = (String)cb.getRuntimeProperties().get(BindingProvider.PASSWORD_PROPERTY);
System.out.println("Got Password : " + password);
cb.setPassword(password);
} else {
throw unsupported;
}
}
}
private class PlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
if ("Ron".equals(plainTextRequest.getUsername()) &&
"noR".equals(plainTextRequest.getPassword())) {
return true;
}
return false;
}
}
}
/*
* SecurityHandler.java
*
* Created on March 26, 2007, 12:58 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.hermit.study.jdk.shello;
import java.io.FileInputStream;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import com.sun.xml.wss.ProcessingContext;
import com.sun.xml.wss.SubjectAccessor;
import com.sun.xml.wss.XWSSProcessor;
import com.sun.xml.wss.XWSSProcessorFactory;
import com.sun.xml.wss.XWSSecurityException;
/**
*
* Kumar Jayanti
*/
public class SecurityHandler implements SOAPHandler<SOAPMessageContext> {
XWSSProcessor sprocessor = null;
XWSSProcessor cprocessor = null;
/** Creates a new instance of SecurityHandler */
public SecurityHandler() {
FileInputStream clientConfig = null;
try {
// read client side security config
clientConfig = new java.io.FileInputStream(new java.io.File("./src/user-pass-authenticate-client.xml"));
// Create a XWSSProcessFactory.
XWSSProcessorFactory factory = XWSSProcessorFactory.newInstance();
cprocessor = factory.createProcessorForSecurityConfiguration(clientConfig, new SecurityEnvironmentHandler("client"));
clientConfig.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public Set<QName> getHeaders() {
return null;
}
public boolean handleFault(SOAPMessageContext messageContext) {
return true;
}
public boolean handleMessage(SOAPMessageContext messageContext) {
System.out.println("This is client");
secureClient(messageContext);
return true;
}
public void close(MessageContext messageContext) {
}
private SOAPMessage createFaultResponse(XWSSecurityException ex) {
return null;
}
private void secureClient(SOAPMessageContext messageContext) {
Boolean outMessageIndicator = (Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
SOAPMessage message = messageContext.getMessage();
System.out.println("Came to Secure Client.");
if (outMessageIndicator.booleanValue()) {
System.out.println("\nOutbound SOAP:");
ProcessingContext context;
try {
context = cprocessor.createProcessingContext(message);
context.getExtraneousProperties().putAll(messageContext);
context.setSOAPMessage(message);
SOAPMessage secureMsg = cprocessor.secureOutboundMessage(context);
secureMsg.writeTo(System.out);
messageContext.setMessage(secureMsg);
} catch (XWSSecurityException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return;
} else {
System.out.println("\nInbound SOAP:");
System.out.println("DO Nothing in Secure Client.");
// do nothing
return;
}
}
}
package org.hermit.study.jdk.shello;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.1 in JDK 6
* Generated source version: 2.1
*
*/
@WebService(name = "SecurityHello", targetNamespace = "http://jdk.study.hermit.org/shello")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface SecurityHello {
/**
*
* @param arg0
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(partName = "return")
public String sayHello(
@WebParam(name = "arg0", partName = "arg0")
String arg0);
}
package org.hermit.study.jdk.shello;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.1 in JDK 6
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "SecurityHelloService", targetNamespace = "http://jdk.study.hermit.org/shello", wsdlLocation = "http://127.0.0.1:8088/SecurityHello?wsdl")
public class SecurityHelloService
extends Service
{
private final static URL SECURITYHELLOSERVICE_WSDL_LOCATION;
static {
URL url = null;
try {
url = new URL("http://127.0.0.1:8088/SecurityHello?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
SECURITYHELLOSERVICE_WSDL_LOCATION = url;
}
public SecurityHelloService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public SecurityHelloService() {
super(SECURITYHELLOSERVICE_WSDL_LOCATION, new QName("http://jdk.study.hermit.org/shello", "SecurityHelloService"));
}
/**
*
* @return
* returns SecurityHello
*/
@WebEndpoint(name = "SecurityHelloPort")
public SecurityHello getSecurityHelloPort() {
return (SecurityHello)super.getPort(new QName("http://jdk.study.hermit.org/shello", "SecurityHelloPort"), SecurityHello.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns SecurityHello
*/
@WebEndpoint(name = "SecurityHelloPort")
public SecurityHello getSecurityHelloPort(WebServiceFeature features) {
return (SecurityHello)super.getPort(new QName("http://jdk.study.hermit.org/shello", "SecurityHelloPort"), SecurityHello.class, features);
}
}
user-pass-authenticate-client.xml
<!--
Copyright 2004 Sun Microsystems, Inc. All rights reserved.
SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
-->
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config" dumpMessages="true" >
<xwss:UsernameToken digestPassword="true"/>
</xwss:SecurityConfiguration>
终于贴完了
报异常
<S:Envelope xmlns:S="
http://schemas.xmlsoap.org/soap/envelope/"><S:Header>
<wsse:Security xmlns:wsse="
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" S:mustUnderstand="1"><wsse:UsernameToken xmlns:wsu="
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="XWSSGID-1212378178718-1762088361"><wsse:Username>hermit</wsse:Username><wsse:Password Type="
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">HmGpnf6+FOReizFMyZMmvOJI3Cs=</wsse:Password><wsse:Nonce EncodingType="
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">PED+zrhDAVFnEYXOC6loZM4i</wsse:Nonce><wsu:Created>2008-06-02T03:42:58.937Z</wsu:Created></wsse:UsernameToken></wsse:Security></S:Header><S:Body><ns2:sayHello xmlns:ns2="
http://jdk.study.hermit.org/shello"><arg0>Hermit</arg0></ns2:sayHello></S:Body></S:Envelope>Exception in thread "main" java.lang.ExceptionInInitializerError
at com.sun.xml.internal.ws.message.AttachmentUnmarshallerImpl.<clinit>(AttachmentUnmarshallerImpl.java:77)
at com.sun.xml.internal.ws.message.stream.StreamMessage.readPayloadAsJAXB(StreamMessage.java:201)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.create(SOAPFaultBuilder.java:463)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:239)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:210)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:103)
at $Proxy22.sayHello(Unknown Source)
at TestSericutyHello.main(TestSericutyHello.java:26)
Caused by: java.lang.IllegalArgumentException: com.sun.xml.messaging.saaj.soap.LocalStrings != com.sun.xml.internal.messaging.saaj.soap.LocalStrings
at java.util.logging.Logger.getLogger(Logger.java:328)
at com.sun.xml.internal.messaging.saaj.soap.AttachmentPartImpl.<clinit>(AttachmentPartImpl.java:71)
... 8 more
google了一下貌似是jdk新版本的bug(Java(TM) SE Runtime Environment (build 1.6.0_06-b02))
http://forums.java.net/jive/thread.jspa?threadID=41696&tstart=0http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6481282希望下个版本能解决这个问题。
posted on 2008-06-02 12:09
交口称赞 阅读(4886)
评论(2) 编辑 收藏 所属分类:
Java6