Converted spaces to tabs

This commit changes leading spaces in all Java source files to tabs, to
be consistent with other Spring projects.
This commit is contained in:
Arjen Poutsma
2015-03-18 09:33:06 +01:00
parent b6500fe5ac
commit 7d64bebd19
824 changed files with 46904 additions and 46904 deletions

View File

@@ -50,216 +50,216 @@ import org.springframework.ws.soap.soap11.Soap11Body;
*/
public abstract class AbstractWsSecurityInterceptor implements SoapEndpointInterceptor, ClientInterceptor {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
protected static final QName WS_SECURITY_NAME =
new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
protected static final QName WS_SECURITY_NAME =
new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
private boolean secureResponse = true;
private boolean secureResponse = true;
private boolean validateRequest = true;
private boolean validateRequest = true;
private boolean secureRequest = true;
private boolean secureRequest = true;
private boolean validateResponse = true;
private boolean skipValidationIfNoHeaderPresent = false;
private boolean validateResponse = true;
private boolean skipValidationIfNoHeaderPresent = false;
private EndpointExceptionResolver exceptionResolver;
private EndpointExceptionResolver exceptionResolver;
/** Indicates whether server-side incoming request are to be validated. Defaults to {@code true}. */
public void setValidateRequest(boolean validateRequest) {
this.validateRequest = validateRequest;
}
/** Indicates whether server-side incoming request are to be validated. Defaults to {@code true}. */
public void setValidateRequest(boolean validateRequest) {
this.validateRequest = validateRequest;
}
/** Indicates whether server-side outgoing responses are to be secured. Defaults to {@code true}. */
public void setSecureResponse(boolean secureResponse) {
this.secureResponse = secureResponse;
}
/** Indicates whether server-side outgoing responses are to be secured. Defaults to {@code true}. */
public void setSecureResponse(boolean secureResponse) {
this.secureResponse = secureResponse;
}
/** Indicates whether client-side outgoing requests are to be secured. Defaults to {@code true}. */
public void setSecureRequest(boolean secureRequest) {
this.secureRequest = secureRequest;
}
/** Indicates whether client-side outgoing requests are to be secured. Defaults to {@code true}. */
public void setSecureRequest(boolean secureRequest) {
this.secureRequest = secureRequest;
}
/** Indicates whether client-side incoming responses are to be validated. Defaults to {@code true}. */
public void setValidateResponse(boolean validateResponse) {
this.validateResponse = validateResponse;
}
/** Indicates whether client-side incoming responses are to be validated. Defaults to {@code true}. */
public void setValidateResponse(boolean validateResponse) {
this.validateResponse = validateResponse;
}
/** Provide an {@link EndpointExceptionResolver} for resolving validation exceptions. */
public void setExceptionResolver(EndpointExceptionResolver exceptionResolver) {
this.exceptionResolver = exceptionResolver;
}
/** Provide an {@link EndpointExceptionResolver} for resolving validation exceptions. */
public void setExceptionResolver(EndpointExceptionResolver exceptionResolver) {
this.exceptionResolver = exceptionResolver;
}
/** Allows skipping validation if no security header is present. */
public void setSkipValidationIfNoHeaderPresent(
/** Allows skipping validation if no security header is present. */
public void setSkipValidationIfNoHeaderPresent(
boolean skipValidationIfNoHeaderPresent) {
this.skipValidationIfNoHeaderPresent = skipValidationIfNoHeaderPresent;
}
/*
* Server-side
*/
/*
* Server-side
*/
/**
* Validates a server-side incoming request. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setValidateRequest(boolean) validateRequest} property is {@code true}.
*
* @param messageContext the message context, containing the request to be validated
* @param endpoint chosen endpoint to invoke
* @return {@code true} if the request was valid; {@code false} otherwise.
* @throws Exception in case of errors
* @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
if (validateRequest) {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest());
if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){
return true;
}
try {
validateMessage((SoapMessage) messageContext.getRequest(), messageContext);
return true;
}
catch (WsSecurityValidationException ex) {
return handleValidationException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
* Validates a server-side incoming request. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setValidateRequest(boolean) validateRequest} property is {@code true}.
*
* @param messageContext the message context, containing the request to be validated
* @param endpoint chosen endpoint to invoke
* @return {@code true} if the request was valid; {@code false} otherwise.
* @throws Exception in case of errors
* @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
if (validateRequest) {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest());
if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){
return true;
}
try {
validateMessage((SoapMessage) messageContext.getRequest(), messageContext);
return true;
}
catch (WsSecurityValidationException ex) {
return handleValidationException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
/**
* Secures a server-side outgoing response. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setSecureResponse(boolean) secureResponse} property is {@code true}.
*
* @param messageContext the message context, containing the response to be secured
* @param endpoint chosen endpoint to invoke
* @return {@code true} if the response was secured; {@code false} otherwise.
* @throws Exception in case of errors
* @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
boolean result = true;
try {
if (secureResponse) {
Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response");
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse());
try {
secureMessage((SoapMessage) messageContext.getResponse(), messageContext);
}
catch (WsSecuritySecurementException ex) {
result = handleSecurementException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
result = handleFaultException(ex, messageContext);
}
}
}
finally {
if (!result) {
messageContext.clearResponse();
}
}
return result;
}
* Secures a server-side outgoing response. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setSecureResponse(boolean) secureResponse} property is {@code true}.
*
* @param messageContext the message context, containing the response to be secured
* @param endpoint chosen endpoint to invoke
* @return {@code true} if the response was secured; {@code false} otherwise.
* @throws Exception in case of errors
* @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
boolean result = true;
try {
if (secureResponse) {
Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response");
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse());
try {
secureMessage((SoapMessage) messageContext.getResponse(), messageContext);
}
catch (WsSecuritySecurementException ex) {
result = handleSecurementException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
result = handleFaultException(ex, messageContext);
}
}
}
finally {
if (!result) {
messageContext.clearResponse();
}
}
return result;
}
/** Returns {@code true}, i.e. fault responses are not secured. */
@Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
/** Returns {@code true}, i.e. fault responses are not secured. */
@Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
@Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) {
cleanUp();
}
@Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) {
cleanUp();
}
@Override
public boolean understands(SoapHeaderElement headerElement) {
return WS_SECURITY_NAME.equals(headerElement.getName());
}
@Override
public boolean understands(SoapHeaderElement headerElement) {
return WS_SECURITY_NAME.equals(headerElement.getName());
}
/*
* Client-side
*/
/*
* Client-side
*/
/**
* Secures a client-side outgoing request. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setSecureRequest(boolean) secureRequest} property is {@code true}.
*
* @param messageContext the message context, containing the request to be secured
* @return {@code true} if the response was secured; {@code false} otherwise.
* @throws Exception in case of errors
* @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
if (secureRequest) {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest());
try {
secureMessage((SoapMessage) messageContext.getRequest(), messageContext);
return true;
}
catch (WsSecuritySecurementException ex) {
return handleSecurementException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
/**
* Secures a client-side outgoing request. Delegates to {@link #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setSecureRequest(boolean) secureRequest} property is {@code true}.
*
* @param messageContext the message context, containing the request to be secured
* @return {@code true} if the response was secured; {@code false} otherwise.
* @throws Exception in case of errors
* @see #secureMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
if (secureRequest) {
Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest());
try {
secureMessage((SoapMessage) messageContext.getRequest(), messageContext);
return true;
}
catch (WsSecuritySecurementException ex) {
return handleSecurementException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
/**
* Validates a client-side incoming response. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setValidateResponse(boolean) validateResponse} property is {@code true}.
*
* @param messageContext the message context, containing the response to be validated
* @return {@code true} if the request was valid; {@code false} otherwise.
* @throws Exception in case of errors
* @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
if (validateResponse) {
Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response");
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse());
if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){
return true;
}
try {
validateMessage((SoapMessage) messageContext.getResponse(), messageContext);
return true;
}
catch (WsSecurityValidationException ex) {
return handleValidationException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
/**
* Validates a client-side incoming response. Delegates to {@link #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)}
* if the {@link #setValidateResponse(boolean) validateResponse} property is {@code true}.
*
* @param messageContext the message context, containing the response to be validated
* @return {@code true} if the request was valid; {@code false} otherwise.
* @throws Exception in case of errors
* @see #validateMessage(org.springframework.ws.soap.SoapMessage,org.springframework.ws.context.MessageContext)
*/
@Override
public final boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
if (validateResponse) {
Assert.isTrue(messageContext.hasResponse(), "MessageContext contains no response");
Assert.isInstanceOf(SoapMessage.class, messageContext.getResponse());
if(skipValidationIfNoHeaderPresent && !isSecurityHeaderPresent((SoapMessage) messageContext.getRequest())){
return true;
}
try {
validateMessage((SoapMessage) messageContext.getResponse(), messageContext);
return true;
}
catch (WsSecurityValidationException ex) {
return handleValidationException(ex, messageContext);
}
catch (WsSecurityFaultException ex) {
return handleFaultException(ex, messageContext);
}
}
else {
return true;
}
}
/** Returns {@code true}, i.e. fault responses are not validated. */
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
return true;
}
/** Returns {@code true}, i.e. fault responses are not validated. */
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
return true;
}
@Override
public void afterCompletion(MessageContext messageContext, Exception ex)
@@ -268,107 +268,107 @@ public abstract class AbstractWsSecurityInterceptor implements SoapEndpointInter
}
/**
* Handles an securement exception. Default implementation logs the given exception, and returns
* {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleSecurementException(WsSecuritySecurementException ex, MessageContext messageContext) {
if (logger.isErrorEnabled()) {
logger.error("Could not secure response: " + ex.getMessage(), ex);
}
return false;
}
* Handles an securement exception. Default implementation logs the given exception, and returns
* {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleSecurementException(WsSecuritySecurementException ex, MessageContext messageContext) {
if (logger.isErrorEnabled()) {
logger.error("Could not secure response: " + ex.getMessage(), ex);
}
return false;
}
/**
* Handles an invalid SOAP message. Default implementation logs the given exception, delegates to the set {@link
* #setExceptionResolver(EndpointExceptionResolver) exceptionResolver} if any, or creates a SOAP 1.1 Client or SOAP
* 1.2 Sender Fault with the exception message as fault string, and returns {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleValidationException(WsSecurityValidationException ex, MessageContext messageContext) {
if (logger.isWarnEnabled()) {
logger.warn("Could not validate request: " + ex.getMessage());
}
if (exceptionResolver != null) {
exceptionResolver.resolveException(messageContext, null, ex);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No exception resolver present, creating basic soap fault");
}
SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody();
response.addClientOrSenderFault(ex.getMessage(), Locale.ENGLISH);
}
return false;
}
/**
* Handles an invalid SOAP message. Default implementation logs the given exception, delegates to the set {@link
* #setExceptionResolver(EndpointExceptionResolver) exceptionResolver} if any, or creates a SOAP 1.1 Client or SOAP
* 1.2 Sender Fault with the exception message as fault string, and returns {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleValidationException(WsSecurityValidationException ex, MessageContext messageContext) {
if (logger.isWarnEnabled()) {
logger.warn("Could not validate request: " + ex.getMessage());
}
if (exceptionResolver != null) {
exceptionResolver.resolveException(messageContext, null, ex);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No exception resolver present, creating basic soap fault");
}
SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody();
response.addClientOrSenderFault(ex.getMessage(), Locale.ENGLISH);
}
return false;
}
/**
* Handles a fault exception.Default implementation logs the given exception, and creates a SOAP Fault with the
* properties of the given exception, and returns {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleFaultException(WsSecurityFaultException ex, MessageContext messageContext) {
if (logger.isWarnEnabled()) {
logger.warn("Could not handle request: " + ex.getMessage());
}
SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody();
SoapFault fault;
if (response instanceof Soap11Body) {
fault = ((Soap11Body) response).addFault(ex.getFaultCode(), ex.getFaultString(), Locale.ENGLISH);
}
else {
fault = response.addClientOrSenderFault(ex.getFaultString(), Locale.ENGLISH);
}
fault.setFaultActorOrRole(ex.getFaultActor());
return false;
}
/**
* Handles a fault exception.Default implementation logs the given exception, and creates a SOAP Fault with the
* properties of the given exception, and returns {@code false}.
*
* @param ex the validation exception
* @param messageContext the message context
* @return {@code true} to continue processing the message, {@code false} (the default) otherwise
*/
protected boolean handleFaultException(WsSecurityFaultException ex, MessageContext messageContext) {
if (logger.isWarnEnabled()) {
logger.warn("Could not handle request: " + ex.getMessage());
}
SoapBody response = ((SoapMessage) messageContext.getResponse()).getSoapBody();
SoapFault fault;
if (response instanceof Soap11Body) {
fault = ((Soap11Body) response).addFault(ex.getFaultCode(), ex.getFaultString(), Locale.ENGLISH);
}
else {
fault = response.addClientOrSenderFault(ex.getFaultString(), Locale.ENGLISH);
}
fault.setFaultActorOrRole(ex.getFaultActor());
return false;
}
/**
* Abstract template method. Subclasses are required to validate the request contained in the given {@link
* SoapMessage}, and replace the original request with the validated version.
*
* @param soapMessage the soap message to validate
* @throws WsSecurityValidationException in case of validation errors
*/
protected abstract void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException;
/**
* Abstract template method. Subclasses are required to validate the request contained in the given {@link
* SoapMessage}, and replace the original request with the validated version.
*
* @param soapMessage the soap message to validate
* @throws WsSecurityValidationException in case of validation errors
*/
protected abstract void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException;
/**
* Abstract template method. Subclasses are required to secure the response contained in the given {@link
* SoapMessage}, and replace the original response with the secured version.
*
* @param soapMessage the soap message to secure
* @throws WsSecuritySecurementException in case of securement errors
*/
protected abstract void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException;
/**
* Abstract template method. Subclasses are required to secure the response contained in the given {@link
* SoapMessage}, and replace the original response with the secured version.
*
* @param soapMessage the soap message to secure
* @throws WsSecuritySecurementException in case of securement errors
*/
protected abstract void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException;
protected abstract void cleanUp();
protected abstract void cleanUp();
/**
* Iterates over header elements and returns true if WS-Security header is found.
*/
private boolean isSecurityHeaderPresent(SoapMessage message) {
SoapHeader soapHeader = message.getSoapHeader();
if(soapHeader == null){
return false;
}
/**
* Iterates over header elements and returns true if WS-Security header is found.
*/
private boolean isSecurityHeaderPresent(SoapMessage message) {
SoapHeader soapHeader = message.getSoapHeader();
if(soapHeader == null){
return false;
}
Iterator<SoapHeaderElement> elements = soapHeader.examineAllHeaderElements();
while(elements.hasNext()){
SoapHeaderElement e = elements.next();
if(e.getName().equals(WS_SECURITY_NAME)){
return true;
}
}
return false;
while(elements.hasNext()){
SoapHeaderElement e = elements.next();
if(e.getName().equals(WS_SECURITY_NAME)){
return true;
}
}
return false;
}
}

View File

@@ -28,11 +28,11 @@ import org.springframework.ws.WebServiceException;
@SuppressWarnings("serial")
public abstract class WsSecurityException extends WebServiceException {
public WsSecurityException(String msg) {
super(msg);
}
public WsSecurityException(String msg) {
super(msg);
}
public WsSecurityException(String msg, Throwable ex) {
super(msg, ex);
}
public WsSecurityException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -27,32 +27,32 @@ import javax.xml.namespace.QName;
@SuppressWarnings("serial")
public abstract class WsSecurityFaultException extends WsSecurityException {
private QName faultCode;
private QName faultCode;
private String faultString;
private String faultString;
private String faultActor;
private String faultActor;
/** Construct a new {@code WsSecurityFaultException} with the given fault code, string, and actor. */
public WsSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultString);
this.faultCode = faultCode;
this.faultString = faultString;
this.faultActor = faultActor;
}
/** Construct a new {@code WsSecurityFaultException} with the given fault code, string, and actor. */
public WsSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultString);
this.faultCode = faultCode;
this.faultString = faultString;
this.faultActor = faultActor;
}
/** Returns the fault code for the exception. */
public QName getFaultCode() {
return faultCode;
}
/** Returns the fault code for the exception. */
public QName getFaultCode() {
return faultCode;
}
/** Returns the fault string for the exception. */
public String getFaultString() {
return faultString;
}
/** Returns the fault string for the exception. */
public String getFaultString() {
return faultString;
}
/** Returns the fault actor for the exception. */
public String getFaultActor() {
return faultActor;
}
/** Returns the fault actor for the exception. */
public String getFaultActor() {
return faultActor;
}
}

View File

@@ -28,11 +28,11 @@ package org.springframework.ws.soap.security;
@SuppressWarnings("serial")
public abstract class WsSecuritySecurementException extends WsSecurityException {
public WsSecuritySecurementException(String msg) {
super(msg);
}
public WsSecuritySecurementException(String msg) {
super(msg);
}
public WsSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
public WsSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -28,11 +28,11 @@ package org.springframework.ws.soap.security;
@SuppressWarnings("serial")
public abstract class WsSecurityValidationException extends WsSecurityException {
public WsSecurityValidationException(String msg) {
super(msg);
}
public WsSecurityValidationException(String msg) {
super(msg);
}
public WsSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
public WsSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -32,25 +32,25 @@ import org.apache.commons.logging.LogFactory;
*/
public abstract class AbstractCallbackHandler implements CallbackHandler {
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
protected AbstractCallbackHandler() {
}
protected AbstractCallbackHandler() {
}
/**
* Iterates over the given callbacks, and calls {@code handleInternal} for each of them.
*
* @param callbacks the callbacks
* @see #handleInternal(javax.security.auth.callback.Callback)
*/
@Override
public final void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
handleInternal(callback);
}
}
/**
* Iterates over the given callbacks, and calls {@code handleInternal} for each of them.
*
* @param callbacks the callbacks
* @see #handleInternal(javax.security.auth.callback.Callback)
*/
@Override
public final void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
handleInternal(callback);
}
}
/** Template method that should be implemented by subclasses. */
protected abstract void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException;
/** Template method that should be implemented by subclasses. */
protected abstract void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException;
}

View File

@@ -30,30 +30,30 @@ import javax.security.auth.callback.UnsupportedCallbackException;
*/
public class CallbackHandlerChain extends AbstractCallbackHandler {
private final CallbackHandler[] callbackHandlers;
private final CallbackHandler[] callbackHandlers;
public CallbackHandlerChain(CallbackHandler[] callbackHandlers) {
this.callbackHandlers = callbackHandlers;
}
public CallbackHandlerChain(CallbackHandler[] callbackHandlers) {
this.callbackHandlers = callbackHandlers;
}
public CallbackHandler[] getCallbackHandlers() {
return callbackHandlers;
}
public CallbackHandler[] getCallbackHandlers() {
return callbackHandlers;
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
boolean allUnsupported = true;
for (CallbackHandler callbackHandler : callbackHandlers) {
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
}
catch (UnsupportedCallbackException ex) {
// if an UnsupportedCallbackException occurs, go to the next handler
}
}
if (allUnsupported) {
throw new UnsupportedCallbackException(callback);
}
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
boolean allUnsupported = true;
for (CallbackHandler callbackHandler : callbackHandlers) {
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
}
catch (UnsupportedCallbackException ex) {
// if an UnsupportedCallbackException occurs, go to the next handler
}
}
if (allUnsupported) {
throw new UnsupportedCallbackException(callback);
}
}
}

View File

@@ -28,6 +28,6 @@ import javax.security.auth.callback.Callback;
*/
public class CleanupCallback implements Callback, Serializable {
private static final long serialVersionUID = 4744181820980888237L;
private static final long serialVersionUID = 4744181820980888237L;
}

View File

@@ -39,75 +39,75 @@ public class KeyManagersFactoryBean implements FactoryBean<KeyManager[]>, Initia
private KeyManager[] keyManagers;
private KeyStore keyStore;
private KeyStore keyStore;
private String algorithm;
private String algorithm;
private String provider;
private String provider;
private char[] password;
private char[] password;
/**
* Sets the password to use for integrity checking. If this property is not set, then integrity checking is not
* performed.
*/
public void setPassword(String password) {
if (password != null) {
this.password = password.toCharArray();
}
}
/**
* Sets the password to use for integrity checking. If this property is not set, then integrity checking is not
* performed.
*/
public void setPassword(String password) {
if (password != null) {
this.password = password.toCharArray();
}
}
/**
* Sets the provider of the key manager to use. If this is not set, the default is used.
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Sets the provider of the key manager to use. If this is not set, the default is used.
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Sets the algorithm of the {@code KeyManager} to use. If this is not set, the default is used.
*
* @see KeyManagerFactory#getDefaultAlgorithm()
*/
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
/**
* Sets the algorithm of the {@code KeyManager} to use. If this is not set, the default is used.
*
* @see KeyManagerFactory#getDefaultAlgorithm()
*/
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
/**
* Sets the source of key material.
*
* @see KeyManagerFactory#init(KeyStore, char[])
*/
public void setKeyStore(KeyStore keyStore) {
this.keyStore = keyStore;
}
/**
* Sets the source of key material.
*
* @see KeyManagerFactory#init(KeyStore, char[])
*/
public void setKeyStore(KeyStore keyStore) {
this.keyStore = keyStore;
}
@Override
public KeyManager[] getObject() throws Exception {
return keyManagers;
}
@Override
public KeyManager[] getObject() throws Exception {
return keyManagers;
}
@Override
public Class<?> getObjectType() {
return KeyManager[].class;
}
@Override
public Class<?> getObjectType() {
return KeyManager[].class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
String algorithm =
StringUtils.hasLength(this.algorithm) ? this.algorithm : KeyManagerFactory.getDefaultAlgorithm();
@Override
public void afterPropertiesSet() throws Exception {
String algorithm =
StringUtils.hasLength(this.algorithm) ? this.algorithm : KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory =
StringUtils.hasLength(this.provider) ? KeyManagerFactory.getInstance(algorithm, this.provider) :
KeyManagerFactory.getInstance(algorithm);
KeyManagerFactory keyManagerFactory =
StringUtils.hasLength(this.provider) ? KeyManagerFactory.getInstance(algorithm, this.provider) :
KeyManagerFactory.getInstance(algorithm);
keyManagerFactory.init(keyStore, password);
keyManagerFactory.init(keyStore, password);
this.keyManagers = keyManagerFactory.getKeyManagers();
}
this.keyManagers = keyManagerFactory.getKeyManagers();
}
}

View File

@@ -42,94 +42,94 @@ import org.springframework.util.StringUtils;
*/
public class KeyStoreFactoryBean implements FactoryBean<KeyStore>, InitializingBean {
private static final Log logger = LogFactory.getLog(KeyStoreFactoryBean.class);
private static final Log logger = LogFactory.getLog(KeyStoreFactoryBean.class);
private KeyStore keyStore;
private KeyStore keyStore;
private String type;
private String type;
private String provider;
private String provider;
private Resource location;
private Resource location;
private char[] password;
private char[] password;
/**
* Sets the location of the key store to use. If this is not set, a new, empty key store will be used.
*
* @see KeyStore#load(java.io.InputStream,char[])
*/
public void setLocation(Resource location) {
this.location = location;
}
/**
* Sets the location of the key store to use. If this is not set, a new, empty key store will be used.
*
* @see KeyStore#load(java.io.InputStream,char[])
*/
public void setLocation(Resource location) {
this.location = location;
}
/**
* Sets the password to use for integrity checking. If this property is not set, then integrity checking is not
* performed.
*/
public void setPassword(String password) {
if (password != null) {
this.password = password.toCharArray();
}
}
/**
* Sets the password to use for integrity checking. If this property is not set, then integrity checking is not
* performed.
*/
public void setPassword(String password) {
if (password != null) {
this.password = password.toCharArray();
}
}
/** Sets the provider of the key store to use. If this is not set, the default is used. */
public void setProvider(String provider) {
this.provider = provider;
}
/** Sets the provider of the key store to use. If this is not set, the default is used. */
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Sets the type of the {@code KeyStore} to use. If this is not set, the default is used.
*
* @see KeyStore#getDefaultType()
*/
public void setType(String type) {
this.type = type;
}
/**
* Sets the type of the {@code KeyStore} to use. If this is not set, the default is used.
*
* @see KeyStore#getDefaultType()
*/
public void setType(String type) {
this.type = type;
}
@Override
public KeyStore getObject() {
return keyStore;
}
@Override
public KeyStore getObject() {
return keyStore;
}
@Override
public Class<KeyStore> getObjectType() {
return KeyStore.class;
}
@Override
public Class<KeyStore> getObjectType() {
return KeyStore.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
keyStore = KeyStore.getInstance(type, provider);
}
else if (StringUtils.hasLength(type)) {
keyStore = KeyStore.getInstance(type);
}
else {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
}
InputStream is = null;
try {
if (location != null && location.exists()) {
is = location.getInputStream();
if (logger.isInfoEnabled()) {
logger.info("Loading key store from " + location);
}
}
else if (logger.isWarnEnabled()) {
logger.warn("Creating empty key store");
}
keyStore.load(is, password);
}
finally {
if (is != null) {
is.close();
}
}
}
@Override
public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
keyStore = KeyStore.getInstance(type, provider);
}
else if (StringUtils.hasLength(type)) {
keyStore = KeyStore.getInstance(type);
}
else {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
}
InputStream is = null;
try {
if (location != null && location.exists()) {
is = location.getInputStream();
if (logger.isInfoEnabled()) {
logger.info("Loading key store from " + location);
}
}
else if (logger.isWarnEnabled()) {
logger.warn("Creating empty key store");
}
keyStore.load(is, password);
}
finally {
if (is != null) {
is.close();
}
}
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -33,91 +33,91 @@ import org.springframework.util.StringUtils;
*/
public abstract class KeyStoreUtils {
/**
* Loads the key store indicated by system properties. This method tries to load a key store by consulting the
* following system properties:{@code javax.net.ssl.keyStore}, {@code javax.net.ssl.keyStorePassword}, and
* {@code javax.net.ssl.keyStoreType}.
*
* <p>If these properties specify a file with an appropriate password, the factory uses this file for the key store. If
* that file does not exist, then a default, empty keystore is created.
*
* <p>This behavior corresponds to the standard J2SDK behavior for SSL key stores.
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html#X509KeyManager">The
* standard J2SDK SSL key store mechanism</a>
*/
public static KeyStore loadDefaultKeyStore() throws GeneralSecurityException, IOException {
Resource location = null;
String type = null;
String password = null;
String locationProperty = System.getProperty("javax.net.ssl.keyStore");
if (StringUtils.hasLength(locationProperty)) {
File f = new File(locationProperty);
if (f.exists() && f.isFile() && f.canRead()) {
location = new FileSystemResource(f);
}
String passwordProperty = System.getProperty("javax.net.ssl.keyStorePassword");
if (StringUtils.hasLength(passwordProperty)) {
password = passwordProperty;
}
type = System.getProperty("javax.net.ssl.keyStoreType");
}
// use the factory bean here, easier to setup
KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean();
factoryBean.setLocation(location);
factoryBean.setPassword(password);
factoryBean.setType(type);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
/**
* Loads the key store indicated by system properties. This method tries to load a key store by consulting the
* following system properties:{@code javax.net.ssl.keyStore}, {@code javax.net.ssl.keyStorePassword}, and
* {@code javax.net.ssl.keyStoreType}.
*
* <p>If these properties specify a file with an appropriate password, the factory uses this file for the key store. If
* that file does not exist, then a default, empty keystore is created.
*
* <p>This behavior corresponds to the standard J2SDK behavior for SSL key stores.
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html#X509KeyManager">The
* standard J2SDK SSL key store mechanism</a>
*/
public static KeyStore loadDefaultKeyStore() throws GeneralSecurityException, IOException {
Resource location = null;
String type = null;
String password = null;
String locationProperty = System.getProperty("javax.net.ssl.keyStore");
if (StringUtils.hasLength(locationProperty)) {
File f = new File(locationProperty);
if (f.exists() && f.isFile() && f.canRead()) {
location = new FileSystemResource(f);
}
String passwordProperty = System.getProperty("javax.net.ssl.keyStorePassword");
if (StringUtils.hasLength(passwordProperty)) {
password = passwordProperty;
}
type = System.getProperty("javax.net.ssl.keyStoreType");
}
// use the factory bean here, easier to setup
KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean();
factoryBean.setLocation(location);
factoryBean.setPassword(password);
factoryBean.setType(type);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
/**
* Loads a default trust store. This method uses the following algorithm: <ol> <li> If the system property
* {@code javax.net.ssl.trustStore} is defined, its value is loaded. If the
* {@code javax.net.ssl.trustStorePassword} system property is also defined, its value is used as a password.
* If the {@code javax.net.ssl.trustStoreType} system property is defined, its value is used as a key store
* type.
*
* <p>If {@code javax.net.ssl.trustStore} is defined but the specified file does not exist, then a default, empty
* trust store is created. </li> <li> If the {@code javax.net.ssl.trustStore} system property was not
* specified, but if the file {@code $JAVA_HOME/lib/security/jssecacerts} exists, that file is used. </li>
* Otherwise, <li>If the file {@code $JAVA_HOME/lib/security/cacerts} exists, that file is used. </ol>
*
* <p>This behavior corresponds to the standard J2SDK behavior for SSL trust stores.
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html#X509TrustManager">The
* standard J2SDK SSL trust store mechanism</a>
*/
public static KeyStore loadDefaultTrustStore() throws GeneralSecurityException, IOException {
Resource location = null;
String type = null;
String password = null;
String locationProperty = System.getProperty("javax.net.ssl.trustStore");
if (StringUtils.hasLength(locationProperty)) {
File f = new File(locationProperty);
if (f.exists() && f.isFile() && f.canRead()) {
location = new FileSystemResource(f);
}
String passwordProperty = System.getProperty("javax.net.ssl.trustStorePassword");
if (StringUtils.hasLength(passwordProperty)) {
password = passwordProperty;
}
type = System.getProperty("javax.net.ssl.trustStoreType");
}
else {
String javaHome = System.getProperty("java.home");
location = new FileSystemResource(javaHome + "/lib/security/jssecacerts");
if (!location.exists()) {
location = new FileSystemResource(javaHome + "/lib/security/cacerts");
}
}
// use the factory bean here, easier to setup
KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean();
factoryBean.setLocation(location);
factoryBean.setPassword(password);
factoryBean.setType(type);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
/**
* Loads a default trust store. This method uses the following algorithm: <ol> <li> If the system property
* {@code javax.net.ssl.trustStore} is defined, its value is loaded. If the
* {@code javax.net.ssl.trustStorePassword} system property is also defined, its value is used as a password.
* If the {@code javax.net.ssl.trustStoreType} system property is defined, its value is used as a key store
* type.
*
* <p>If {@code javax.net.ssl.trustStore} is defined but the specified file does not exist, then a default, empty
* trust store is created. </li> <li> If the {@code javax.net.ssl.trustStore} system property was not
* specified, but if the file {@code $JAVA_HOME/lib/security/jssecacerts} exists, that file is used. </li>
* Otherwise, <li>If the file {@code $JAVA_HOME/lib/security/cacerts} exists, that file is used. </ol>
*
* <p>This behavior corresponds to the standard J2SDK behavior for SSL trust stores.
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/jsse/JSSERefGuide.html#X509TrustManager">The
* standard J2SDK SSL trust store mechanism</a>
*/
public static KeyStore loadDefaultTrustStore() throws GeneralSecurityException, IOException {
Resource location = null;
String type = null;
String password = null;
String locationProperty = System.getProperty("javax.net.ssl.trustStore");
if (StringUtils.hasLength(locationProperty)) {
File f = new File(locationProperty);
if (f.exists() && f.isFile() && f.canRead()) {
location = new FileSystemResource(f);
}
String passwordProperty = System.getProperty("javax.net.ssl.trustStorePassword");
if (StringUtils.hasLength(passwordProperty)) {
password = passwordProperty;
}
type = System.getProperty("javax.net.ssl.trustStoreType");
}
else {
String javaHome = System.getProperty("java.home");
location = new FileSystemResource(javaHome + "/lib/security/jssecacerts");
if (!location.exists()) {
location = new FileSystemResource(javaHome + "/lib/security/cacerts");
}
}
// use the factory bean here, easier to setup
KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean();
factoryBean.setLocation(location);
factoryBean.setPassword(password);
factoryBean.setType(type);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
}

View File

@@ -30,31 +30,31 @@ import org.springframework.security.core.userdetails.UserDetails;
*/
public abstract class SpringSecurityUtils {
/**
* Checks the validity of a user's account and credentials.
* @param user the user to check
* @throws AccountExpiredException if the account has expired
* @throws CredentialsExpiredException if the credentials have expired
* @throws DisabledException if the account is disabled
* @throws LockedException if the account is locked
*/
@SuppressWarnings("deprecation")
public static void checkUserValidity(UserDetails user)
throws AccountExpiredException, CredentialsExpiredException, DisabledException, LockedException {
if (!user.isAccountNonLocked()) {
throw new LockedException("User account is locked", user);
}
/**
* Checks the validity of a user's account and credentials.
* @param user the user to check
* @throws AccountExpiredException if the account has expired
* @throws CredentialsExpiredException if the credentials have expired
* @throws DisabledException if the account is disabled
* @throws LockedException if the account is locked
*/
@SuppressWarnings("deprecation")
public static void checkUserValidity(UserDetails user)
throws AccountExpiredException, CredentialsExpiredException, DisabledException, LockedException {
if (!user.isAccountNonLocked()) {
throw new LockedException("User account is locked", user);
}
if (!user.isEnabled()) {
throw new DisabledException("User is disabled", user);
}
if (!user.isEnabled()) {
throw new DisabledException("User is disabled", user);
}
if (!user.isAccountNonExpired()) {
throw new AccountExpiredException("User account has expired", user);
}
if (!user.isAccountNonExpired()) {
throw new AccountExpiredException("User account has expired", user);
}
if (!user.isCredentialsNonExpired()) {
throw new CredentialsExpiredException("User credentials have expired", user);
}
}
if (!user.isCredentialsNonExpired()) {
throw new CredentialsExpiredException("User credentials have expired", user);
}
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -36,87 +36,87 @@ import org.w3c.dom.Document;
*/
class Wss4jHandler extends WSHandler {
/** Keys are constants from {@link WSHandlerConstants}; values are strings. */
private Properties options = new Properties();
/** Keys are constants from {@link WSHandlerConstants}; values are strings. */
private Properties options = new Properties();
private String securementPassword;
private String securementPassword;
private Crypto securementEncryptionCrypto;
private Crypto securementEncryptionCrypto;
private Crypto securementSignatureCrypto;
private Crypto securementSignatureCrypto;
Wss4jHandler() {
// set up default handler properties
options.setProperty(WSHandlerConstants.MUST_UNDERSTAND, Boolean.toString(true));
options.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, Boolean.toString(true));
}
Wss4jHandler() {
// set up default handler properties
options.setProperty(WSHandlerConstants.MUST_UNDERSTAND, Boolean.toString(true));
options.setProperty(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION, Boolean.toString(true));
}
@Override
protected boolean checkReceiverResultsAnyOrder(List<WSSecurityEngineResult> wsResult, List<Integer> actions) {
return super.checkReceiverResultsAnyOrder(wsResult, actions);
}
@Override
protected boolean checkReceiverResultsAnyOrder(List<WSSecurityEngineResult> wsResult, List<Integer> actions) {
return super.checkReceiverResultsAnyOrder(wsResult, actions);
}
void setOption(String key, String value) {
options.setProperty(key, value);
}
void setOption(String key, String value) {
options.setProperty(key, value);
}
void setOption(String key, boolean value) {
options.setProperty(key, Boolean.toString(value));
}
void setOption(String key, boolean value) {
options.setProperty(key, Boolean.toString(value));
}
@Override
public Object getOption(String key) {
return options.getProperty(key);
}
@Override
public Object getOption(String key) {
return options.getProperty(key);
}
void setSecurementPassword(String securementPassword) {
this.securementPassword = securementPassword;
}
void setSecurementPassword(String securementPassword) {
this.securementPassword = securementPassword;
}
void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) {
this.securementEncryptionCrypto = securementEncryptionCrypto;
}
void setSecurementEncryptionCrypto(Crypto securementEncryptionCrypto) {
this.securementEncryptionCrypto = securementEncryptionCrypto;
}
void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) {
this.securementSignatureCrypto = securementSignatureCrypto;
}
void setSecurementSignatureCrypto(Crypto securementSignatureCrypto) {
this.securementSignatureCrypto = securementSignatureCrypto;
}
@Override
public String getPassword(Object msgContext) {
return securementPassword;
}
@Override
public String getPassword(Object msgContext) {
return securementPassword;
}
@Override
public Object getProperty(Object msgContext, String key) {
return ((MessageContext) msgContext).getProperty(key);
}
@Override
public Object getProperty(Object msgContext, String key) {
return ((MessageContext) msgContext).getProperty(key);
}
@Override
protected Crypto loadEncryptionCrypto(RequestData reqData) throws WSSecurityException {
return securementEncryptionCrypto;
}
@Override
protected Crypto loadEncryptionCrypto(RequestData reqData) throws WSSecurityException {
return securementEncryptionCrypto;
}
@Override
public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException {
return securementSignatureCrypto;
}
@Override
public Crypto loadSignatureCrypto(RequestData reqData) throws WSSecurityException {
return securementSignatureCrypto;
}
@Override
public void setPassword(Object msgContext, String password) {
securementPassword = password;
}
@Override
public void setPassword(Object msgContext, String password) {
securementPassword = password;
}
@Override
public void setProperty(Object msgContext, String key, Object value) {
((MessageContext) msgContext).setProperty(key, value);
}
@Override
public void setProperty(Object msgContext, String key, Object value) {
((MessageContext) msgContext).setProperty(key, value);
}
@Override
protected void doSenderAction(int doAction,
Document doc,
RequestData reqData,
List<Integer> actions,
boolean isRequest) throws WSSecurityException {
super.doSenderAction(doAction, doc, reqData, actions, isRequest);
}
@Override
protected void doSenderAction(int doAction,
Document doc,
RequestData reqData,
List<Integer> actions,
boolean isRequest) throws WSSecurityException {
super.doSenderAction(doAction, doc, reqData, actions, isRequest);
}
}

View File

@@ -30,7 +30,7 @@ import org.springframework.ws.soap.security.WsSecurityFaultException;
@SuppressWarnings("serial")
public class Wss4jSecurityFaultException extends WsSecurityFaultException {
public Wss4jSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultCode, faultString, faultActor);
}
public Wss4jSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultCode, faultString, faultActor);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -28,12 +28,12 @@ import org.springframework.ws.soap.security.WsSecuritySecurementException;
@SuppressWarnings("serial")
public class Wss4jSecuritySecurementException extends WsSecuritySecurementException {
public Wss4jSecuritySecurementException(String msg) {
super(msg);
}
public Wss4jSecuritySecurementException(String msg) {
super(msg);
}
public Wss4jSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
public Wss4jSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -28,12 +28,12 @@ import org.springframework.ws.soap.security.WsSecurityValidationException;
@SuppressWarnings("serial")
public class Wss4jSecurityValidationException extends WsSecurityValidationException {
public Wss4jSecurityValidationException(String msg) {
super(msg);
}
public Wss4jSecurityValidationException(String msg) {
super(msg);
}
public Wss4jSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
public Wss4jSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -34,137 +34,137 @@ import org.apache.ws.security.WSPasswordCallback;
*/
public abstract class AbstractWsPasswordCallbackHandler extends AbstractCallbackHandler {
/**
* Handles {@link WSPasswordCallback} callbacks. Inspects the callback {@link WSPasswordCallback#getUsage() usage}
* code, and calls the various {@code handle*} template methods.
*
* @param callback the callback
* @throws IOException in case of I/O errors
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof WSPasswordCallback) {
WSPasswordCallback passwordCallback = (WSPasswordCallback) callback;
switch (passwordCallback.getUsage()) {
case WSPasswordCallback.DECRYPT:
handleDecrypt(passwordCallback);
break;
case WSPasswordCallback.USERNAME_TOKEN:
handleUsernameToken(passwordCallback);
break;
case WSPasswordCallback.SIGNATURE:
handleSignature(passwordCallback);
break;
case WSPasswordCallback.SECURITY_CONTEXT_TOKEN:
handleSecurityContextToken(passwordCallback);
break;
case WSPasswordCallback.CUSTOM_TOKEN:
handleCustomToken(passwordCallback);
break;
case WSPasswordCallback.SECRET_KEY:
handleSecretKey(passwordCallback);
break;
default:
throw new UnsupportedCallbackException(callback,
"Unknown usage [" + passwordCallback.getUsage() + "]");
}
}
else if (callback instanceof CleanupCallback) {
handleCleanup((CleanupCallback) callback);
}
else if (callback instanceof UsernameTokenPrincipalCallback) {
handleUsernameTokenPrincipal((UsernameTokenPrincipalCallback) callback);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Handles {@link WSPasswordCallback} callbacks. Inspects the callback {@link WSPasswordCallback#getUsage() usage}
* code, and calls the various {@code handle*} template methods.
*
* @param callback the callback
* @throws IOException in case of I/O errors
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof WSPasswordCallback) {
WSPasswordCallback passwordCallback = (WSPasswordCallback) callback;
switch (passwordCallback.getUsage()) {
case WSPasswordCallback.DECRYPT:
handleDecrypt(passwordCallback);
break;
case WSPasswordCallback.USERNAME_TOKEN:
handleUsernameToken(passwordCallback);
break;
case WSPasswordCallback.SIGNATURE:
handleSignature(passwordCallback);
break;
case WSPasswordCallback.SECURITY_CONTEXT_TOKEN:
handleSecurityContextToken(passwordCallback);
break;
case WSPasswordCallback.CUSTOM_TOKEN:
handleCustomToken(passwordCallback);
break;
case WSPasswordCallback.SECRET_KEY:
handleSecretKey(passwordCallback);
break;
default:
throw new UnsupportedCallbackException(callback,
"Unknown usage [" + passwordCallback.getUsage() + "]");
}
}
else if (callback instanceof CleanupCallback) {
handleCleanup((CleanupCallback) callback);
}
else if (callback instanceof UsernameTokenPrincipalCallback) {
handleUsernameTokenPrincipal((UsernameTokenPrincipalCallback) callback);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#DECRYPT} usage.
*
* <p>This method is invoked when WSS4J needs a password to get the private key of the {@link
* WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to
* decrypt the session (symmetric) key. Because the encryption method uses the public key to encrypt the session key
* it needs no password (a public key is usually not protected by a password).
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#DECRYPT} usage.
*
* <p>This method is invoked when WSS4J needs a password to get the private key of the {@link
* WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to
* decrypt the session (symmetric) key. Because the encryption method uses the public key to encrypt the session key
* it needs no password (a public key is usually not protected by a password).
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#USERNAME_TOKEN} usage.
*
* <p>This method is invoked when WSS4J needs the password to fill in or to verify a UsernameToken.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#USERNAME_TOKEN} usage.
*
* <p>This method is invoked when WSS4J needs the password to fill in or to verify a UsernameToken.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SIGNATURE} usage.
*
* <p>This method is invoked when WSS4J needs the password to get the private key of the {@link
* WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to
* produce a signature. The signature verfication uses the public key to verfiy the signature.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSignature(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SIGNATURE} usage.
*
* <p>This method is invoked when WSS4J needs the password to get the private key of the {@link
* WSPasswordCallback#getIdentifier() identifier} (username) from the keystore. WSS4J uses this private key to
* produce a signature. The signature verfication uses the public key to verfiy the signature.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSignature(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SECURITY_CONTEXT_TOKEN} usage.
*
* <p>This method is invoked when WSS4J needs the key to to be associated with a SecurityContextToken.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSecurityContextToken(WSPasswordCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SECURITY_CONTEXT_TOKEN} usage.
*
* <p>This method is invoked when WSS4J needs the key to to be associated with a SecurityContextToken.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSecurityContextToken(WSPasswordCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#CUSTOM_TOKEN} usage.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleCustomToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#CUSTOM_TOKEN} usage.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleCustomToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SECRET_KEY} usage.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when the callback has a {@link WSPasswordCallback#SECRET_KEY} usage.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when a {@link CleanupCallback} is passed to {@link #handle(Callback[])}.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when a {@link CleanupCallback} is passed to {@link #handle(Callback[])}.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when a {@link UsernameTokenPrincipalCallback} is passed to {@link #handle(Callback[])}.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Invoked when a {@link UsernameTokenPrincipalCallback} is passed to {@link #handle(Callback[])}.
*
* <p>Default implementation throws an {@link UnsupportedCallbackException}.
*/
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
}

View File

@@ -39,83 +39,83 @@ import org.springframework.ws.soap.security.support.KeyStoreUtils;
*/
public class KeyStoreCallbackHandler extends AbstractWsPasswordCallbackHandler implements InitializingBean {
private String privateKeyPassword;
private String privateKeyPassword;
private char[] symmetricKeyPassword;
private char[] symmetricKeyPassword;
private KeyStore keyStore;
private KeyStore keyStore;
/** Sets the key store to use if a symmetric key name is embedded. */
public void setKeyStore(KeyStore keyStore) {
this.keyStore = keyStore;
}
/** Sets the key store to use if a symmetric key name is embedded. */
public void setKeyStore(KeyStore keyStore) {
this.keyStore = keyStore;
}
/**
* Sets the password used to retrieve private keys from the keystore. This property is required for decryption based
* on private keys, and signing.
*/
public void setPrivateKeyPassword(String privateKeyPassword) {
if (privateKeyPassword != null) {
this.privateKeyPassword = privateKeyPassword;
}
}
/**
* Sets the password used to retrieve private keys from the keystore. This property is required for decryption based
* on private keys, and signing.
*/
public void setPrivateKeyPassword(String privateKeyPassword) {
if (privateKeyPassword != null) {
this.privateKeyPassword = privateKeyPassword;
}
}
/**
* Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it defaults to
* the private key password.
*
* @see #setPrivateKeyPassword(String)
*/
public void setSymmetricKeyPassword(String symmetricKeyPassword) {
if (symmetricKeyPassword != null) {
this.symmetricKeyPassword = symmetricKeyPassword.toCharArray();
}
}
/**
* Sets the password used to retrieve keys from the symmetric keystore. If this property is not set, it defaults to
* the private key password.
*
* @see #setPrivateKeyPassword(String)
*/
public void setSymmetricKeyPassword(String symmetricKeyPassword) {
if (symmetricKeyPassword != null) {
this.symmetricKeyPassword = symmetricKeyPassword.toCharArray();
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (keyStore == null) {
loadDefaultKeyStore();
}
if (symmetricKeyPassword == null) {
symmetricKeyPassword = privateKeyPassword.toCharArray();
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (keyStore == null) {
loadDefaultKeyStore();
}
if (symmetricKeyPassword == null) {
symmetricKeyPassword = privateKeyPassword.toCharArray();
}
}
@Override
protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
callback.setPassword(privateKeyPassword);
}
@Override
protected void handleDecrypt(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
callback.setPassword(privateKeyPassword);
}
@Override
protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
try {
String identifier = callback.getIdentifier();
Key key = keyStore.getKey(identifier, symmetricKeyPassword);
if (key instanceof SecretKey) {
callback.setKey(key.getEncoded());
}
else {
logger.error("Key [" + key + "] is not a javax.crypto.SecretKey");
}
}
catch (GeneralSecurityException ex) {
logger.error("Could not obtain symmetric key", ex);
}
}
@Override
protected void handleSecretKey(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
try {
String identifier = callback.getIdentifier();
Key key = keyStore.getKey(identifier, symmetricKeyPassword);
if (key instanceof SecretKey) {
callback.setKey(key.getEncoded());
}
else {
logger.error("Key [" + key + "] is not a javax.crypto.SecretKey");
}
}
catch (GeneralSecurityException ex) {
logger.error("Could not obtain symmetric key", ex);
}
}
/** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */
protected void loadDefaultKeyStore() {
try {
keyStore = KeyStoreUtils.loadDefaultKeyStore();
if (logger.isDebugEnabled()) {
logger.debug("Loaded default key store");
}
}
catch (Exception ex) {
logger.warn("Could not open default key store", ex);
}
}
/** Loads the key store indicated by system properties. Delegates to {@link KeyStoreUtils#loadDefaultKeyStore()}. */
protected void loadDefaultKeyStore() {
try {
keyStore = KeyStoreUtils.loadDefaultKeyStore();
if (logger.isDebugEnabled()) {
logger.debug("Loaded default key store");
}
}
catch (Exception ex) {
logger.warn("Could not open default key store", ex);
}
}
}

View File

@@ -37,32 +37,32 @@ import org.springframework.util.Assert;
* @since 1.5.0
*/
public class SimplePasswordValidationCallbackHandler extends AbstractWsPasswordCallbackHandler
implements InitializingBean {
implements InitializingBean {
private Map<String, String > users = new HashMap<String, String>();
private Map<String, String > users = new HashMap<String, String>();
/** Sets the users to validate against. Property names are usernames, property values are passwords. */
public void setUsers(Properties users) {
for (Map.Entry<Object, Object> entry : users.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
this.users.put((String) entry.getKey(), (String) entry.getValue());
}
}
}
/** Sets the users to validate against. Property names are usernames, property values are passwords. */
public void setUsers(Properties users) {
for (Map.Entry<Object, Object> entry : users.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
this.users.put((String) entry.getKey(), (String) entry.getValue());
}
}
}
public void setUsersMap(Map<String, String> users) {
this.users = users;
}
public void setUsersMap(Map<String, String> users) {
this.users = users;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(users, "users is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(users, "users is required");
}
@Override
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
String identifier = callback.getIdentifier();
callback.setPassword(users.get(identifier));
}
@Override
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
String identifier = callback.getIdentifier();
callback.setPassword(users.get(identifier));
}
}

View File

@@ -45,70 +45,70 @@ import org.springframework.ws.soap.security.support.SpringSecurityUtils;
* @since 2.1
*/
public class SpringSecurityPasswordValidationCallbackHandler extends AbstractWsPasswordCallbackHandler
implements InitializingBean {
implements InitializingBean {
private UserCache userCache = new NullUserCache();
private UserCache userCache = new NullUserCache();
private UserDetailsService userDetailsService;
private UserDetailsService userDetailsService;
/** Sets the users cache. Not required, but can benefit performance. */
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
/** Sets the users cache. Not required, but can benefit performance. */
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
/** Sets the Spring Security user details service. Required. */
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/** Sets the Spring Security user details service. Required. */
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "userDetailsService is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "userDetailsService is required");
}
@Override
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
String identifier = callback.getIdentifier();
UserDetails user = loadUserDetails(identifier);
if (user != null) {
SpringSecurityUtils.checkUserValidity(user);
callback.setPassword(user.getPassword());
}
}
@Override
protected void handleUsernameToken(WSPasswordCallback callback) throws IOException, UnsupportedCallbackException {
String identifier = callback.getIdentifier();
UserDetails user = loadUserDetails(identifier);
if (user != null) {
SpringSecurityUtils.checkUserValidity(user);
callback.setPassword(user.getPassword());
}
}
@Override
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback)
throws IOException, UnsupportedCallbackException {
UserDetails user = loadUserDetails(callback.getPrincipal().getName());
WSUsernameTokenPrincipal principal = callback.getPrincipal();
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), user.getAuthorities());
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authRequest.toString());
}
SecurityContextHolder.getContext().setAuthentication(authRequest);
}
@Override
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback)
throws IOException, UnsupportedCallbackException {
UserDetails user = loadUserDetails(callback.getPrincipal().getName());
WSUsernameTokenPrincipal principal = callback.getPrincipal();
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), user.getAuthorities());
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authRequest.toString());
}
SecurityContextHolder.getContext().setAuthentication(authRequest);
}
@Override
protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException {
SecurityContextHolder.clearContext();
}
@Override
protected void handleCleanup(CleanupCallback callback) throws IOException, UnsupportedCallbackException {
SecurityContextHolder.clearContext();
}
private UserDetails loadUserDetails(String username) throws DataAccessException {
UserDetails user = userCache.getUserFromCache(username);
private UserDetails loadUserDetails(String username) throws DataAccessException {
UserDetails user = userCache.getUserFromCache(username);
if (user == null) {
try {
user = userDetailsService.loadUserByUsername(username);
}
catch (UsernameNotFoundException notFound) {
if (logger.isDebugEnabled()) {
logger.debug("Username '" + username + "' not found");
}
return null;
}
userCache.putUserInCache(user);
}
return user;
}
if (user == null) {
try {
user = userDetailsService.loadUserByUsername(username);
}
catch (UsernameNotFoundException notFound) {
if (logger.isDebugEnabled()) {
logger.debug("Username '" + username + "' not found");
}
return null;
}
userCache.putUserInCache(user);
}
return user;
}
}

View File

@@ -32,17 +32,17 @@ import org.apache.ws.security.WSUsernameTokenPrincipal;
*/
public class UsernameTokenPrincipalCallback implements Callback, Serializable {
private static final long serialVersionUID = -3022202225157082715L;
private static final long serialVersionUID = -3022202225157082715L;
private final WSUsernameTokenPrincipal principal;
private final WSUsernameTokenPrincipal principal;
/** Construct a {@code UsernameTokenPrincipalCallback}. */
public UsernameTokenPrincipalCallback(WSUsernameTokenPrincipal principal) {
this.principal = principal;
}
/** Construct a {@code UsernameTokenPrincipalCallback}. */
public UsernameTokenPrincipalCallback(WSUsernameTokenPrincipal principal) {
this.principal = principal;
}
/** Get the retrieved {@code Principal}. */
public WSUsernameTokenPrincipal getPrincipal() {
return principal;
}
/** Get the retrieved {@code Principal}. */
public WSUsernameTokenPrincipal getPrincipal() {
return principal;
}
}

View File

@@ -44,151 +44,151 @@ import org.springframework.util.Assert;
*/
public class CryptoFactoryBean implements FactoryBean<Crypto>, BeanClassLoaderAware, InitializingBean {
private Properties configuration = new Properties();
private Properties configuration = new Properties();
private ClassLoader classLoader;
private ClassLoader classLoader;
private Crypto crypto;
private Crypto crypto;
private static final String CRYPTO_PROVIDER_PROPERTY = "org.apache.ws.security.crypto.provider";
private static final String CRYPTO_PROVIDER_PROPERTY = "org.apache.ws.security.crypto.provider";
/**
* Sets the configuration of the Crypto. Setting this property overrides all previously set configuration, through
* the type-safe properties
*
* @see org.apache.ws.security.components.crypto.CryptoFactory#getInstance(java.util.Properties)
*/
public void setConfiguration(Properties properties) {
Assert.notNull(properties, "'properties' must not be null");
this.configuration.putAll(properties);
}
/**
* Sets the configuration of the Crypto. Setting this property overrides all previously set configuration, through
* the type-safe properties
*
* @see org.apache.ws.security.components.crypto.CryptoFactory#getInstance(java.util.Properties)
*/
public void setConfiguration(Properties properties) {
Assert.notNull(properties, "'properties' must not be null");
this.configuration.putAll(properties);
}
/**
* Sets the {@link org.apache.ws.security.components.crypto.Crypto} provider name. Defaults to {@link
* org.apache.ws.security.components.crypto.Merlin}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.provider} property.
*
* @param cryptoProviderClass the crypto provider class
*/
public void setCryptoProvider(Class<? extends Crypto> cryptoProviderClass) {
this.configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, cryptoProviderClass.getName());
}
/**
* Sets the {@link org.apache.ws.security.components.crypto.Crypto} provider name. Defaults to {@link
* org.apache.ws.security.components.crypto.Merlin}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.provider} property.
*
* @param cryptoProviderClass the crypto provider class
*/
public void setCryptoProvider(Class<? extends Crypto> cryptoProviderClass) {
this.configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, cryptoProviderClass.getName());
}
/**
* Sets the location of the key store to be loaded in the {@link org.apache.ws.security.components.crypto.Crypto}
* instance.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.file} property.
*
* @param location the key store location
* @throws java.io.IOException when the resource cannot be opened
*/
public void setKeyStoreLocation(Resource location) throws IOException {
String resourcePath = getResourcePath(location);
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.file", resourcePath);
}
/**
* Sets the location of the key store to be loaded in the {@link org.apache.ws.security.components.crypto.Crypto}
* instance.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.file} property.
*
* @param location the key store location
* @throws java.io.IOException when the resource cannot be opened
*/
public void setKeyStoreLocation(Resource location) throws IOException {
String resourcePath = getResourcePath(location);
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.file", resourcePath);
}
private String getResourcePath(Resource resource) throws IOException {
try {
return resource.getFile().getAbsolutePath();
}
catch (IOException ex) {
if (resource instanceof ClassPathResource) {
ClassPathResource classPathResource = (ClassPathResource) resource;
return classPathResource.getPath();
}
else {
throw ex;
}
}
}
private String getResourcePath(Resource resource) throws IOException {
try {
return resource.getFile().getAbsolutePath();
}
catch (IOException ex) {
if (resource instanceof ClassPathResource) {
ClassPathResource classPathResource = (ClassPathResource) resource;
return classPathResource.getPath();
}
else {
throw ex;
}
}
}
/**
* Sets the key store provider.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.provider} property.
*
* @param provider the key store provider
*/
public void setKeyStoreProvider(String provider) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.provider", provider);
}
/**
* Sets the key store provider.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.provider} property.
*
* @param provider the key store provider
*/
public void setKeyStoreProvider(String provider) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.provider", provider);
}
/**
* Sets the key store password. Defaults to {@code security}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.password} property.
*
* @param password the key store password
*/
public void setKeyStorePassword(String password) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", password);
}
/**
* Sets the key store password. Defaults to {@code security}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.password} property.
*
* @param password the key store password
*/
public void setKeyStorePassword(String password) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", password);
}
/**
* Sets the key store type. Defaults to {@link java.security.KeyStore#getDefaultType()}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.type} property.
*
* @param type the key store type
*/
public void setKeyStoreType(String type) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", type);
}
/**
* Sets the key store type. Defaults to {@link java.security.KeyStore#getDefaultType()}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.type} property.
*
* @param type the key store type
*/
public void setKeyStoreType(String type) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", type);
}
/**
* Sets the trust store password. Defaults to {@code changeit}.
*
* <p>WSS4J crypto uses the standard J2SE trust store, i.e. {@code $JAVA_HOME/lib/security/cacerts}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.cacerts.password} property.
*
* @param password the trust store password
*/
public void setTrustStorePassword(String password) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.cacerts.password", password);
}
/**
* Sets the trust store password. Defaults to {@code changeit}.
*
* <p>WSS4J crypto uses the standard J2SE trust store, i.e. {@code $JAVA_HOME/lib/security/cacerts}.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.cacerts.password} property.
*
* @param password the trust store password
*/
public void setTrustStorePassword(String password) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.cacerts.password", password);
}
/**
* Sets the alias name of the default certificate which has been specified as a property. This should be the
* certificate that is used for signature and encryption. This alias corresponds to the certificate that should be
* used whenever KeyInfo is not present in a signed or an encrypted message.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.alias} property.
*
* @param defaultX509Alias alias name of the default X509 certificate
*/
public void setDefaultX509Alias(String defaultX509Alias) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", defaultX509Alias);
}
/**
* Sets the alias name of the default certificate which has been specified as a property. This should be the
* certificate that is used for signature and encryption. This alias corresponds to the certificate that should be
* used whenever KeyInfo is not present in a signed or an encrypted message.
*
* <p>This property maps to the WSS4J {@code org.apache.ws.security.crypto.merlin.keystore.alias} property.
*
* @param defaultX509Alias alias name of the default X509 certificate
*/
public void setDefaultX509Alias(String defaultX509Alias) {
this.configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.alias", defaultX509Alias);
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
public void afterPropertiesSet() throws Exception {
if (!configuration.containsKey(CRYPTO_PROVIDER_PROPERTY)) {
configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, Merlin.class.getName());
}
this.crypto = CryptoFactory.getInstance(configuration, classLoader);
}
@Override
public void afterPropertiesSet() throws Exception {
if (!configuration.containsKey(CRYPTO_PROVIDER_PROPERTY)) {
configuration.setProperty(CRYPTO_PROVIDER_PROPERTY, Merlin.class.getName());
}
this.crypto = CryptoFactory.getInstance(configuration, classLoader);
}
@Override
public Class<Crypto> getObjectType() {
return Crypto.class;
}
@Override
public Class<Crypto> getObjectType() {
return Crypto.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public Crypto getObject() throws Exception {
return crypto;
}
@Override
public Crypto getObject() throws Exception {
return crypto;
}
}

View File

@@ -44,89 +44,89 @@ import org.springframework.ws.soap.security.x509.cache.X509UserCache;
* @version $Id: X509AuthenticationProvider.java 3256 2008-08-18 18:20:48Z luke_t $
*/
public class X509AuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(X509AuthenticationProvider.class);
private static final Log logger = LogFactory.getLog(X509AuthenticationProvider.class);
//~ Instance fields ================================================================================================
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private X509AuthoritiesPopulator x509AuthoritiesPopulator;
private X509UserCache userCache = new NullX509UserCache();
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private X509AuthoritiesPopulator x509AuthoritiesPopulator;
private X509UserCache userCache = new NullX509UserCache();
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userCache, "An x509UserCache must be set");
Assert.notNull(x509AuthoritiesPopulator, "An X509AuthoritiesPopulator must be set");
Assert.notNull(this.messages, "A message source must be set");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userCache, "An x509UserCache must be set");
Assert.notNull(x509AuthoritiesPopulator, "An X509AuthoritiesPopulator must be set");
Assert.notNull(this.messages, "A message source must be set");
}
/**
* If the supplied authentication token contains a certificate then this will be passed to the configured
* {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
* certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
* which client authentication hasn't been configured in the container) then a BadCredentialsException will be
* raised.</p>
*
* @param authentication the authentication request.
*
* @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
*
* @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
* @throws BadCredentialsException if no certificate was presented in the authentication request.
*/
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
/**
* If the supplied authentication token contains a certificate then this will be passed to the configured
* {@link X509AuthoritiesPopulator} to obtain the user details and authorities for the user identified by the
* certificate.<p>If no certificate is present (for example, if the filter is applied to an HttpRequest for
* which client authentication hasn't been configured in the container) then a BadCredentialsException will be
* raised.</p>
*
* @param authentication the authentication request.
*
* @return an X509AuthenticationToken containing the authorities of the principal represented by the certificate.
*
* @throws AuthenticationException if the {@link X509AuthoritiesPopulator} rejects the certficate.
* @throws BadCredentialsException if no certificate was presented in the authentication request.
*/
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("X509 authentication request: " + authentication);
}
if (logger.isDebugEnabled()) {
logger.debug("X509 authentication request: " + authentication);
}
X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();
X509Certificate clientCertificate = (X509Certificate) authentication.getCredentials();
if (clientCertificate == null) {
throw new BadCredentialsException(messages.getMessage("X509AuthenticationProvider.certificateNull",
"Certificate is null"));
}
if (clientCertificate == null) {
throw new BadCredentialsException(messages.getMessage("X509AuthenticationProvider.certificateNull",
"Certificate is null"));
}
UserDetails user = userCache.getUserFromCache(clientCertificate);
UserDetails user = userCache.getUserFromCache(clientCertificate);
if (user == null) {
if (logger.isDebugEnabled()) {
logger.debug("Authenticating with certificate " + clientCertificate);
}
user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
userCache.putUserInCache(clientCertificate, user);
}
if (user == null) {
if (logger.isDebugEnabled()) {
logger.debug("Authenticating with certificate " + clientCertificate);
}
user = x509AuthoritiesPopulator.getUserDetails(clientCertificate);
userCache.putUserInCache(clientCertificate, user);
}
X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate, user.getAuthorities());
X509AuthenticationToken result = new X509AuthenticationToken(user, clientCertificate, user.getAuthorities());
result.setDetails(authentication.getDetails());
result.setDetails(authentication.getDetails());
return result;
}
return result;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setX509AuthoritiesPopulator(X509AuthoritiesPopulator x509AuthoritiesPopulator) {
this.x509AuthoritiesPopulator = x509AuthoritiesPopulator;
}
public void setX509AuthoritiesPopulator(X509AuthoritiesPopulator x509AuthoritiesPopulator) {
this.x509AuthoritiesPopulator = x509AuthoritiesPopulator;
}
public void setX509UserCache(X509UserCache cache) {
this.userCache = cache;
}
public void setX509UserCache(X509UserCache cache) {
this.userCache = cache;
}
@Override
public boolean supports(Class<?> authentication) {
return X509AuthenticationToken.class.isAssignableFrom(authentication);
}
@Override
public boolean supports(Class<?> authentication) {
return X509AuthenticationToken.class.isAssignableFrom(authentication);
}
}

View File

@@ -30,50 +30,50 @@ import org.springframework.security.core.GrantedAuthority;
* @author Luke Taylor
*/
public class X509AuthenticationToken extends AbstractAuthenticationToken {
//~ Instance fields ================================================================================================
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private Object principal;
private X509Certificate credentials;
private static final long serialVersionUID = 1L;
private Object principal;
private X509Certificate credentials;
//~ Constructors ===================================================================================================
//~ Constructors ===================================================================================================
/**
* Used for an authentication request. The {@link org.springframework.security.core.Authentication#isAuthenticated()} will return
* {@code false}.
*
* @param credentials the certificate
*/
public X509AuthenticationToken(X509Certificate credentials) {
super(null);
this.credentials = credentials;
}
/**
* Used for an authentication request. The {@link org.springframework.security.core.Authentication#isAuthenticated()} will return
* {@code false}.
*
* @param credentials the certificate
*/
public X509AuthenticationToken(X509Certificate credentials) {
super(null);
this.credentials = credentials;
}
/**
* Used for an authentication response object. The {@link org.springframework.security.core.Authentication#isAuthenticated()}
* will return {@code true}.
*
* @param principal the principal, which is generally a
* {@code UserDetails}
* @param credentials the certificate
* @param authorities the authorities
*/
public X509AuthenticationToken(Object principal, X509Certificate credentials, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(true);
}
/**
* Used for an authentication response object. The {@link org.springframework.security.core.Authentication#isAuthenticated()}
* will return {@code true}.
*
* @param principal the principal, which is generally a
* {@code UserDetails}
* @param credentials the certificate
* @param authorities the authorities
*/
public X509AuthenticationToken(Object principal, X509Certificate credentials, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(true);
}
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
@Override
public Object getCredentials() {
return credentials;
}
@Override
public Object getCredentials() {
return credentials;
}
@Override
public Object getPrincipal() {
return principal;
}
@Override
public Object getPrincipal() {
return principal;
}
}

View File

@@ -36,19 +36,19 @@ import org.springframework.security.core.userdetails.UserDetails;
* @author Luke Taylor
*/
public interface X509AuthoritiesPopulator {
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
/**
* Obtains the granted authorities for the specified user.<p>May throw any
* {@code AuthenticationException} or return {@code null} if the authorities are unavailable.</p>
*
* @param userCertificate the X.509 certificate supplied
*
* @return the details of the indicated user (at minimum the granted authorities and the username)
*
* @throws AuthenticationException if the user details are not available or the certificate isn't valid for the
* application's purpose.
*/
UserDetails getUserDetails(X509Certificate userCertificate)
throws AuthenticationException;
/**
* Obtains the granted authorities for the specified user.<p>May throw any
* {@code AuthenticationException} or return {@code null} if the authorities are unavailable.</p>
*
* @param userCertificate the X.509 certificate supplied
*
* @return the details of the indicated user (at minimum the granted authorities and the username)
*
* @throws AuthenticationException if the user details are not available or the certificate isn't valid for the
* application's purpose.
*/
UserDetails getUserDetails(X509Certificate userCertificate)
throws AuthenticationException;
}

View File

@@ -39,69 +39,69 @@ import org.springframework.util.Assert;
* @author Ben Alex
*/
public class EhCacheBasedX509UserCache implements X509UserCache, InitializingBean {
//~ Static fields/initializers =====================================================================================
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class);
private static final Log logger = LogFactory.getLog(EhCacheBasedX509UserCache.class);
//~ Instance fields ================================================================================================
//~ Instance fields ================================================================================================
private Ehcache cache;
private Ehcache cache;
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "cache is mandatory");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "cache is mandatory");
}
@Override
public UserDetails getUserFromCache(X509Certificate userCert) {
Element element = null;
@Override
public UserDetails getUserFromCache(X509Certificate userCert) {
Element element = null;
try {
element = cache.get(userCert);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage());
}
try {
element = cache.get(userCert);
} catch (CacheException cacheException) {
throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage());
}
if (logger.isDebugEnabled()) {
String subjectDN = "unknown";
if (logger.isDebugEnabled()) {
String subjectDN = "unknown";
if ((userCert != null) && (userCert.getSubjectDN() != null)) {
subjectDN = userCert.getSubjectDN().toString();
}
if ((userCert != null) && (userCert.getSubjectDN() != null)) {
subjectDN = userCert.getSubjectDN().toString();
}
logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN);
}
logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN);
}
if (element == null) {
return null;
} else {
return (UserDetails) element.getObjectValue();
}
}
if (element == null) {
return null;
} else {
return (UserDetails) element.getObjectValue();
}
}
@Override
public void putUserInCache(X509Certificate userCert, UserDetails user) {
Element element = new Element(userCert, user);
@Override
public void putUserInCache(X509Certificate userCert, UserDetails user) {
Element element = new Element(userCert, user);
if (logger.isDebugEnabled()) {
logger.debug("Cache put: " + userCert.getSubjectDN());
}
if (logger.isDebugEnabled()) {
logger.debug("Cache put: " + userCert.getSubjectDN());
}
cache.put(element);
}
cache.put(element);
}
@Override
public void removeUserFromCache(X509Certificate userCert) {
if (logger.isDebugEnabled()) {
logger.debug("Cache remove: " + userCert.getSubjectDN());
}
@Override
public void removeUserFromCache(X509Certificate userCert) {
if (logger.isDebugEnabled()) {
logger.debug("Cache remove: " + userCert.getSubjectDN());
}
cache.remove(userCert);
}
cache.remove(userCert);
}
public void setCache(Ehcache cache) {
this.cache = cache;
}
public void setCache(Ehcache cache) {
this.cache = cache;
}
}

View File

@@ -28,16 +28,16 @@ import org.springframework.security.core.userdetails.UserDetails;
* @author Luke Taylor
*/
public class NullX509UserCache implements X509UserCache {
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
@Override
public UserDetails getUserFromCache(X509Certificate certificate) {
return null;
}
@Override
public UserDetails getUserFromCache(X509Certificate certificate) {
return null;
}
@Override
public void putUserInCache(X509Certificate certificate, UserDetails user) {}
@Override
public void putUserInCache(X509Certificate certificate, UserDetails user) {}
@Override
public void removeUserFromCache(X509Certificate certificate) {}
@Override
public void removeUserFromCache(X509Certificate certificate) {}
}

View File

@@ -34,11 +34,11 @@ import org.springframework.security.core.userdetails.UserDetails;
* @author Luke Taylor
*/
public interface X509UserCache {
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
UserDetails getUserFromCache(X509Certificate userCertificate);
UserDetails getUserFromCache(X509Certificate userCertificate);
void putUserInCache(X509Certificate key, UserDetails user);
void putUserInCache(X509Certificate key, UserDetails user);
void removeUserFromCache(X509Certificate key);
void removeUserFromCache(X509Certificate key);
}

View File

@@ -44,74 +44,74 @@ import org.springframework.ws.soap.security.x509.X509AuthoritiesPopulator;
* @version $Id: DaoX509AuthoritiesPopulator.java 2544 2008-01-29 11:50:33Z luke_t $
*/
public class DaoX509AuthoritiesPopulator implements X509AuthoritiesPopulator, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(DaoX509AuthoritiesPopulator.class);
private static final Log logger = LogFactory.getLog(DaoX509AuthoritiesPopulator.class);
//~ Instance fields ================================================================================================
//~ Instance fields ================================================================================================
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private Pattern subjectDNPattern;
private String subjectDNRegex = "CN=(.*?),";
private UserDetailsService userDetailsService;
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private Pattern subjectDNPattern;
private String subjectDNRegex = "CN=(.*?),";
private UserDetailsService userDetailsService;
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "An authenticationDao must be set");
Assert.notNull(this.messages, "A message source must be set");
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "An authenticationDao must be set");
Assert.notNull(this.messages, "A message source must be set");
subjectDNPattern = Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE);
}
subjectDNPattern = Pattern.compile(subjectDNRegex, Pattern.CASE_INSENSITIVE);
}
@Override
public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException {
String subjectDN = clientCert.getSubjectDN().getName();
@Override
public UserDetails getUserDetails(X509Certificate clientCert) throws AuthenticationException {
String subjectDN = clientCert.getSubjectDN().getName();
Matcher matcher = subjectDNPattern.matcher(subjectDN);
Matcher matcher = subjectDNPattern.matcher(subjectDN);
if (!matcher.find()) {
throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching",
new Object[] {subjectDN}, "No matching pattern was found in subjectDN: {0}"));
}
if (!matcher.find()) {
throw new BadCredentialsException(messages.getMessage("DaoX509AuthoritiesPopulator.noMatching",
new Object[] {subjectDN}, "No matching pattern was found in subjectDN: {0}"));
}
if (matcher.groupCount() != 1) {
throw new IllegalArgumentException("Regular expression must contain a single group ");
}
if (matcher.groupCount() != 1) {
throw new IllegalArgumentException("Regular expression must contain a single group ");
}
String userName = matcher.group(1);
String userName = matcher.group(1);
UserDetails user = this.userDetailsService.loadUserByUsername(userName);
UserDetails user = this.userDetailsService.loadUserByUsername(userName);
if (user == null) {
throw new AuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
if (user == null) {
throw new AuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return user;
}
return user;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the regular expression which will by used to extract the user name from the certificate's Subject
* DN.
* <p>It should contain a single group; for example the default expression "CN=(.?)," matches the common
* name field. So "CN=Jimi Hendrix, OU=..." will give a user name of "Jimi Hendrix".</p>
* <p>The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org,
* CN=..." giving a user name "jimi@hendrix.org"</p>
*
* @param subjectDNRegex the regular expression to find in the subject
*/
public void setSubjectDNRegex(String subjectDNRegex) {
this.subjectDNRegex = subjectDNRegex;
}
/**
* Sets the regular expression which will by used to extract the user name from the certificate's Subject
* DN.
* <p>It should contain a single group; for example the default expression "CN=(.?)," matches the common
* name field. So "CN=Jimi Hendrix, OU=..." will give a user name of "Jimi Hendrix".</p>
* <p>The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=jimi@hendrix.org,
* CN=..." giving a user name "jimi@hendrix.org"</p>
*
* @param subjectDNRegex the regular expression to find in the subject
*/
public void setSubjectDNRegex(String subjectDNRegex) {
this.subjectDNRegex = subjectDNRegex;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}

View File

@@ -29,7 +29,7 @@ import org.springframework.ws.soap.security.WsSecurityFaultException;
@SuppressWarnings("serial")
public class XwsSecurityFaultException extends WsSecurityFaultException {
public XwsSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultCode, faultString, faultActor);
}
public XwsSecurityFaultException(QName faultCode, String faultString, String faultActor) {
super(faultCode, faultString, faultActor);
}
}

View File

@@ -42,7 +42,7 @@ import org.springframework.ws.soap.security.callback.CleanupCallback;
import org.springframework.ws.soap.security.xwss.callback.XwssCallbackHandlerChain;
/**
* WS-Security endpoint interceptor that is based on Sun's XML and Web Services Security package (XWSS). This
* WS-Security endpoint interceptor that is based on Sun's XML and Web Services Security package (XWSS). This
* WS-Security implementation is part of the Java Web Services Developer Pack (Java WSDP).
*
* <p>This interceptor needs a {@code CallbackHandler} to operate. This handler is used to retrieve certificates,
@@ -66,111 +66,111 @@ import org.springframework.ws.soap.security.xwss.callback.XwssCallbackHandlerCha
*/
public class XwsSecurityInterceptor extends AbstractWsSecurityInterceptor implements InitializingBean {
private XWSSProcessor processor;
private XWSSProcessor processor;
private CallbackHandler callbackHandler;
private CallbackHandler callbackHandler;
private Resource policyConfiguration;
private Resource policyConfiguration;
/**
* Sets the handler to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is
* required.
*
* @see com.sun.xml.wss.impl.callback.XWSSCallback
* @see #setCallbackHandlers(javax.security.auth.callback.CallbackHandler[])
*/
public void setCallbackHandler(CallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
/**
* Sets the handler to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is
* required.
*
* @see com.sun.xml.wss.impl.callback.XWSSCallback
* @see #setCallbackHandlers(javax.security.auth.callback.CallbackHandler[])
*/
public void setCallbackHandler(CallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
/**
* Sets the handlers to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is
* required.
*
* @see com.sun.xml.wss.impl.callback.XWSSCallback
* @see #setCallbackHandler(javax.security.auth.callback.CallbackHandler)
*/
public void setCallbackHandlers(CallbackHandler[] callbackHandler) {
this.callbackHandler = new XwssCallbackHandlerChain(callbackHandler);
}
/**
* Sets the handlers to resolve XWSS callbacks. Setting either this propery, or {@code callbackHandlers}, is
* required.
*
* @see com.sun.xml.wss.impl.callback.XWSSCallback
* @see #setCallbackHandler(javax.security.auth.callback.CallbackHandler)
*/
public void setCallbackHandlers(CallbackHandler[] callbackHandler) {
this.callbackHandler = new XwssCallbackHandlerChain(callbackHandler);
}
/** Sets the policy configuration to use for XWSS. Required. */
public void setPolicyConfiguration(Resource policyConfiguration) {
this.policyConfiguration = policyConfiguration;
}
/** Sets the policy configuration to use for XWSS. Required. */
public void setPolicyConfiguration(Resource policyConfiguration) {
this.policyConfiguration = policyConfiguration;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(policyConfiguration, "policyConfiguration is required");
Assert.isTrue(policyConfiguration.exists(), "policyConfiguration [" + policyConfiguration + "] does not exist");
Assert.notNull(callbackHandler, "callbackHandler is required");
XWSSProcessorFactory processorFactory = XWSSProcessorFactory.newInstance();
InputStream is = null;
try {
if (logger.isInfoEnabled()) {
logger.info("Loading policy configuration from from '" + policyConfiguration + "'");
}
is = policyConfiguration.getInputStream();
processor = processorFactory.createProcessorForSecurityConfiguration(is, callbackHandler);
}
finally {
if (is != null) {
is.close();
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(policyConfiguration, "policyConfiguration is required");
Assert.isTrue(policyConfiguration.exists(), "policyConfiguration [" + policyConfiguration + "] does not exist");
Assert.notNull(callbackHandler, "callbackHandler is required");
XWSSProcessorFactory processorFactory = XWSSProcessorFactory.newInstance();
InputStream is = null;
try {
if (logger.isInfoEnabled()) {
logger.info("Loading policy configuration from from '" + policyConfiguration + "'");
}
is = policyConfiguration.getInputStream();
processor = processorFactory.createProcessorForSecurityConfiguration(is, callbackHandler);
}
finally {
if (is != null) {
is.close();
}
}
}
/**
* Secures the given SoapMessage message in accordance with the defined security policy.
*
* @param soapMessage the message to be secured
* @throws XwsSecuritySecurementException in case of errors
* @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage}
*/
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " +
"Use a SaajSoapMessageFactory to create the SOAP messages.");
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
try {
ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage());
SOAPMessage result = processor.secureOutboundMessage(context);
saajSoapMessage.setSaajMessage(result);
}
catch (XWSSecurityException ex) {
throw new XwsSecuritySecurementException(ex.getMessage(), ex);
}
catch (WssSoapFaultException ex) {
throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor());
}
}
/**
* Secures the given SoapMessage message in accordance with the defined security policy.
*
* @param soapMessage the message to be secured
* @throws XwsSecuritySecurementException in case of errors
* @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage}
*/
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " +
"Use a SaajSoapMessageFactory to create the SOAP messages.");
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
try {
ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage());
SOAPMessage result = processor.secureOutboundMessage(context);
saajSoapMessage.setSaajMessage(result);
}
catch (XWSSecurityException ex) {
throw new XwsSecuritySecurementException(ex.getMessage(), ex);
}
catch (WssSoapFaultException ex) {
throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor());
}
}
/**
* Validates the given SoapMessage message in accordance with the defined security policy.
*
* @param soapMessage the message to be validated
* @throws XwsSecurityValidationException in case of errors
* @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage}
*/
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " +
"Use a SaajSoapMessageFactory to create the SOAP messages.");
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
try {
ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage());
SOAPMessage result = processor.verifyInboundMessage(context);
saajSoapMessage.setSaajMessage(result);
}
catch (XWSSecurityException ex) {
throw new XwsSecurityValidationException(ex.getMessage(), ex);
}
catch (WssSoapFaultException ex) {
throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor());
}
}
/**
* Validates the given SoapMessage message in accordance with the defined security policy.
*
* @param soapMessage the message to be validated
* @throws XwsSecurityValidationException in case of errors
* @throws IllegalArgumentException when soapMessage is not a {@code SaajSoapMessage}
*/
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
Assert.isTrue(soapMessage instanceof SaajSoapMessage, "XwsSecurityInterceptor requires a SaajSoapMessage. " +
"Use a SaajSoapMessageFactory to create the SOAP messages.");
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
try {
ProcessingContext context = processor.createProcessingContext(saajSoapMessage.getSaajMessage());
SOAPMessage result = processor.verifyInboundMessage(context);
saajSoapMessage.setSaajMessage(result);
}
catch (XWSSecurityException ex) {
throw new XwsSecurityValidationException(ex.getMessage(), ex);
}
catch (WssSoapFaultException ex) {
throw new XwsSecurityFaultException(ex.getFaultCode(), ex.getFaultString(), ex.getFaultActor());
}
}
private SOAPMessage verifyInboundMessage(ProcessingContext context)
throws XWSSecurityException {
@@ -191,18 +191,18 @@ public class XwsSecurityInterceptor extends AbstractWsSecurityInterceptor implem
}
@Override
protected void cleanUp() {
if (callbackHandler != null) {
try {
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handle(new Callback[]{cleanupCallback});
}
catch (IOException ex) {
logger.warn("Cleanup callback resulted in IOException", ex);
}
catch (UnsupportedCallbackException ex) {
// ignore
}
}
}
protected void cleanUp() {
if (callbackHandler != null) {
try {
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handle(new Callback[]{cleanupCallback});
}
catch (IOException ex) {
logger.warn("Cleanup callback resulted in IOException", ex);
}
catch (UnsupportedCallbackException ex) {
// ignore
}
}
}
}

View File

@@ -27,11 +27,11 @@ import org.springframework.ws.soap.security.WsSecuritySecurementException;
@SuppressWarnings("serial")
public class XwsSecuritySecurementException extends WsSecuritySecurementException {
public XwsSecuritySecurementException(String msg) {
super(msg);
}
public XwsSecuritySecurementException(String msg) {
super(msg);
}
public XwsSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
public XwsSecuritySecurementException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -27,11 +27,11 @@ import org.springframework.ws.soap.security.WsSecurityValidationException;
@SuppressWarnings("serial")
public class XwsSecurityValidationException extends WsSecurityValidationException {
public XwsSecurityValidationException(String msg) {
super(msg);
}
public XwsSecurityValidationException(String msg) {
super(msg);
}
public XwsSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
public XwsSecurityValidationException(String msg, Throwable ex) {
super(msg, ex);
}
}

View File

@@ -38,458 +38,458 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class CryptographyCallbackHandler extends AbstractCallbackHandler {
@Override
protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
handleCertificateValidationCallback((CertificateValidationCallback) callback);
}
else if (callback instanceof DecryptionKeyCallback) {
handleDecryptionKeyCallback((DecryptionKeyCallback) callback);
}
else if (callback instanceof EncryptionKeyCallback) {
handleEncryptionKeyCallback((EncryptionKeyCallback) callback);
}
else if (callback instanceof SignatureKeyCallback) {
handleSignatureKeyCallback((SignatureKeyCallback) callback);
}
else if (callback instanceof SignatureVerificationKeyCallback) {
handleSignatureVerificationKeyCallback((SignatureVerificationKeyCallback) callback);
}
else {
throw new UnsupportedCallbackException(callback);
}
@Override
protected final void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
handleCertificateValidationCallback((CertificateValidationCallback) callback);
}
else if (callback instanceof DecryptionKeyCallback) {
handleDecryptionKeyCallback((DecryptionKeyCallback) callback);
}
else if (callback instanceof EncryptionKeyCallback) {
handleEncryptionKeyCallback((EncryptionKeyCallback) callback);
}
else if (callback instanceof SignatureKeyCallback) {
handleSignatureKeyCallback((SignatureKeyCallback) callback);
}
else if (callback instanceof SignatureVerificationKeyCallback) {
handleSignatureVerificationKeyCallback((SignatureVerificationKeyCallback) callback);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
}
//
// Certificate validation
//
//
// Certificate validation
//
/**
* Template method that handles {@code CertificateValidationCallback}s. Called from
* {@code handleInternal()}. Default implementation throws an {@code UnsupportedCallbackException}.
*/
protected void handleCertificateValidationCallback(CertificateValidationCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code CertificateValidationCallback}s. Called from
* {@code handleInternal()}. Default implementation throws an {@code UnsupportedCallbackException}.
*/
protected void handleCertificateValidationCallback(CertificateValidationCallback callback)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
//
// Decryption
//
//
// Decryption
//
/**
* Method that handles {@code DecryptionKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handlePrivateKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.PrivateKeyRequest)
* @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.SymmetricKeyRequest)
*/
protected final void handleDecryptionKeyCallback(DecryptionKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof DecryptionKeyCallback.PrivateKeyRequest) {
handlePrivateKeyRequest(callback, (DecryptionKeyCallback.PrivateKeyRequest) callback.getRequest());
}
else if (callback.getRequest() instanceof DecryptionKeyCallback.SymmetricKeyRequest) {
handleSymmetricKeyRequest(callback, (DecryptionKeyCallback.SymmetricKeyRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code DecryptionKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handlePrivateKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.PrivateKeyRequest)
* @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.SymmetricKeyRequest)
*/
protected final void handleDecryptionKeyCallback(DecryptionKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof DecryptionKeyCallback.PrivateKeyRequest) {
handlePrivateKeyRequest(callback, (DecryptionKeyCallback.PrivateKeyRequest) callback.getRequest());
}
else if (callback.getRequest() instanceof DecryptionKeyCallback.SymmetricKeyRequest) {
handleSymmetricKeyRequest(callback, (DecryptionKeyCallback.SymmetricKeyRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code DecryptionKeyCallback}s with {@code PrivateKeyRequest} . Called from
* {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest)
* @see #handleX509CertificateBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509CertificateBasedRequest)
* @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509IssuerSerialBasedRequest)
* @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest)
*/
protected final void handlePrivateKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.PrivateKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) {
handlePublicKeyBasedPrivKeyRequest(callback, (DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509CertificateBasedRequest) {
handleX509CertificateBasedRequest(callback, (DecryptionKeyCallback.X509CertificateBasedRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509IssuerSerialBasedRequest) {
handleX509IssuerSerialBasedRequest(callback, (DecryptionKeyCallback.X509IssuerSerialBasedRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
handleX509SubjectKeyIdentifierBasedRequest(callback,
(DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code DecryptionKeyCallback}s with {@code PrivateKeyRequest} . Called from
* {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest)
* @see #handleX509CertificateBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509CertificateBasedRequest)
* @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509IssuerSerialBasedRequest)
* @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest)
*/
protected final void handlePrivateKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.PrivateKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) {
handlePublicKeyBasedPrivKeyRequest(callback, (DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509CertificateBasedRequest) {
handleX509CertificateBasedRequest(callback, (DecryptionKeyCallback.X509CertificateBasedRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509IssuerSerialBasedRequest) {
handleX509IssuerSerialBasedRequest(callback, (DecryptionKeyCallback.X509IssuerSerialBasedRequest) request);
}
else if (request instanceof DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
handleX509SubjectKeyIdentifierBasedRequest(callback,
(DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code PublicKeyBasedPrivKeyRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code PublicKeyBasedPrivKeyRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedPrivKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.PublicKeyBasedPrivKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509CertificateBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509CertificateBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509CertificateBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509CertificateBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509CertificateBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509CertificateBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509IssuerSerialBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509IssuerSerialBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509IssuerSerialBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509IssuerSerialBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509IssuerSerialBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509SubjectKeyIdentifierBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code X509SubjectKeyIdentifierBasedRequest}s.
* Called from {@code handlePrivateKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509SubjectKeyIdentifierBasedRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.X509SubjectKeyIdentifierBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Method that handles {@code DecryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from
* {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.AliasSymmetricKeyRequest)
*/
protected final void handleSymmetricKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.SymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof DecryptionKeyCallback.AliasSymmetricKeyRequest) {
DecryptionKeyCallback.AliasSymmetricKeyRequest aliasSymmetricKeyRequest =
(DecryptionKeyCallback.AliasSymmetricKeyRequest) request;
handleAliasSymmetricKeyRequest(callback, aliasSymmetricKeyRequest);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code DecryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from
* {@code handleDecryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.DecryptionKeyCallback,
* com.sun.xml.wss.impl.callback.DecryptionKeyCallback.AliasSymmetricKeyRequest)
*/
protected final void handleSymmetricKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.SymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof DecryptionKeyCallback.AliasSymmetricKeyRequest) {
DecryptionKeyCallback.AliasSymmetricKeyRequest aliasSymmetricKeyRequest =
(DecryptionKeyCallback.AliasSymmetricKeyRequest) request;
handleAliasSymmetricKeyRequest(callback, aliasSymmetricKeyRequest);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s.
* Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.AliasSymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code DecryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s.
* Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasSymmetricKeyRequest(DecryptionKeyCallback callback,
DecryptionKeyCallback.AliasSymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
//
// Encryption
//
//
// Encryption
//
/**
* Method that handles {@code EncryptionKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.SymmetricKeyRequest)
* @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.X509CertificateRequest)
*/
protected final void handleEncryptionKeyCallback(EncryptionKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof EncryptionKeyCallback.SymmetricKeyRequest) {
handleSymmetricKeyRequest(callback, (EncryptionKeyCallback.SymmetricKeyRequest) callback.getRequest());
}
else if (callback.getRequest() instanceof EncryptionKeyCallback.X509CertificateRequest) {
handleX509CertificateRequest(callback,
(EncryptionKeyCallback.X509CertificateRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
/**
* Method that handles {@code EncryptionKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handleSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.SymmetricKeyRequest)
* @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.X509CertificateRequest)
*/
protected final void handleEncryptionKeyCallback(EncryptionKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof EncryptionKeyCallback.SymmetricKeyRequest) {
handleSymmetricKeyRequest(callback, (EncryptionKeyCallback.SymmetricKeyRequest) callback.getRequest());
}
else if (callback.getRequest() instanceof EncryptionKeyCallback.X509CertificateRequest) {
handleX509CertificateRequest(callback,
(EncryptionKeyCallback.X509CertificateRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
}
}
/**
* Method that handles {@code EncryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from
* {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasSymmetricKeyRequest)
*/
protected final void handleSymmetricKeyRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.SymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof EncryptionKeyCallback.AliasSymmetricKeyRequest) {
handleAliasSymmetricKeyRequest(callback, (EncryptionKeyCallback.AliasSymmetricKeyRequest) request);
}
}
/**
* Method that handles {@code EncryptionKeyCallback}s with {@code SymmetricKeyRequest} . Called from
* {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasSymmetricKeyRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasSymmetricKeyRequest)
*/
protected final void handleSymmetricKeyRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.SymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof EncryptionKeyCallback.AliasSymmetricKeyRequest) {
handleAliasSymmetricKeyRequest(callback, (EncryptionKeyCallback.AliasSymmetricKeyRequest) request);
}
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s.
* Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.AliasSymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code AliasSymmetricKeyRequest}s.
* Called from {@code handleSymmetricKeyRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasSymmetricKeyRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.AliasSymmetricKeyRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Method that handles {@code EncryptionKeyCallback}s with {@code X509CertificateRequest} . Called from
* {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasX509CertificateRequest)
* @see #handleDefaultX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.DefaultX509CertificateRequest)
* @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.PublicKeyBasedRequest)
*/
protected final void handleX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.X509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
handleAliasX509CertificateRequest(callback, (EncryptionKeyCallback.AliasX509CertificateRequest) request);
}
else if (request instanceof EncryptionKeyCallback.DefaultX509CertificateRequest) {
handleDefaultX509CertificateRequest(callback,
(EncryptionKeyCallback.DefaultX509CertificateRequest) request);
}
else if (request instanceof EncryptionKeyCallback.PublicKeyBasedRequest) {
handlePublicKeyBasedRequest(callback, (EncryptionKeyCallback.PublicKeyBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code EncryptionKeyCallback}s with {@code X509CertificateRequest} . Called from
* {@code handleEncryptionKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleAliasX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.AliasX509CertificateRequest)
* @see #handleDefaultX509CertificateRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.DefaultX509CertificateRequest)
* @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.EncryptionKeyCallback,
* com.sun.xml.wss.impl.callback.EncryptionKeyCallback.PublicKeyBasedRequest)
*/
protected final void handleX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.X509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
handleAliasX509CertificateRequest(callback, (EncryptionKeyCallback.AliasX509CertificateRequest) request);
}
else if (request instanceof EncryptionKeyCallback.DefaultX509CertificateRequest) {
handleDefaultX509CertificateRequest(callback,
(EncryptionKeyCallback.DefaultX509CertificateRequest) request);
}
else if (request instanceof EncryptionKeyCallback.PublicKeyBasedRequest) {
handlePublicKeyBasedRequest(callback, (EncryptionKeyCallback.PublicKeyBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code AliasX509CertificateRequest}s.
* Called from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.AliasX509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code AliasX509CertificateRequest}s.
* Called from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.AliasX509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code DefaultX509CertificateRequest}s.
* Called from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.DefaultX509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code DefaultX509CertificateRequest}s.
* Called from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleDefaultX509CertificateRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.DefaultX509CertificateRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code PublicKeyBasedRequest}s. Called
* from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.PublicKeyBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code EncryptionKeyCallback}s with {@code PublicKeyBasedRequest}s. Called
* from {@code handleX509CertificateRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedRequest(EncryptionKeyCallback callback,
EncryptionKeyCallback.PublicKeyBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
//
// Signing
//
//
// Signing
//
/**
* Method that handles {@code SignatureKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handlePrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PrivKeyCertRequest)
*/
protected final void handleSignatureKeyCallback(SignatureKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof SignatureKeyCallback.PrivKeyCertRequest) {
handlePrivKeyCertRequest(callback, (SignatureKeyCallback.PrivKeyCertRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code SignatureKeyCallback}s. Called from {@code handleInternal()}. Default
* implementation delegates to specific handling methods.
*
* @see #handlePrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PrivKeyCertRequest)
*/
protected final void handleSignatureKeyCallback(SignatureKeyCallback callback)
throws IOException, UnsupportedCallbackException {
if (callback.getRequest() instanceof SignatureKeyCallback.PrivKeyCertRequest) {
handlePrivKeyCertRequest(callback, (SignatureKeyCallback.PrivKeyCertRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code SignatureKeyCallback}s with {@code PrivKeyCertRequest}s. Called from
* {@code handleSignatureKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleDefaultPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.DefaultPrivKeyCertRequest)
* @see #handleAliasPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.AliasPrivKeyCertRequest)
* @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest)
*/
protected final void handlePrivKeyCertRequest(SignatureKeyCallback cb,
SignatureKeyCallback.PrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) {
handleDefaultPrivKeyCertRequest(cb, (SignatureKeyCallback.DefaultPrivKeyCertRequest) request);
}
else if (cb.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) {
handleAliasPrivKeyCertRequest(cb, (SignatureKeyCallback.AliasPrivKeyCertRequest) request);
}
else if (cb.getRequest() instanceof SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) {
handlePublicKeyBasedPrivKeyCertRequest(cb, (SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) request);
}
else {
throw new UnsupportedCallbackException(cb);
}
}
/**
* Method that handles {@code SignatureKeyCallback}s with {@code PrivKeyCertRequest}s. Called from
* {@code handleSignatureKeyCallback()}. Default implementation delegates to specific handling methods.
*
* @see #handleDefaultPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.DefaultPrivKeyCertRequest)
* @see #handleAliasPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.AliasPrivKeyCertRequest)
* @see #handlePublicKeyBasedPrivKeyCertRequest(com.sun.xml.wss.impl.callback.SignatureKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest)
*/
protected final void handlePrivKeyCertRequest(SignatureKeyCallback cb,
SignatureKeyCallback.PrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
if (request instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) {
handleDefaultPrivKeyCertRequest(cb, (SignatureKeyCallback.DefaultPrivKeyCertRequest) request);
}
else if (cb.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) {
handleAliasPrivKeyCertRequest(cb, (SignatureKeyCallback.AliasPrivKeyCertRequest) request);
}
else if (cb.getRequest() instanceof SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) {
handlePublicKeyBasedPrivKeyCertRequest(cb, (SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest) request);
}
else {
throw new UnsupportedCallbackException(cb);
}
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code DefaultPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.DefaultPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code DefaultPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleDefaultPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.DefaultPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code AliasPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.AliasPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code AliasPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleAliasPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.AliasPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedPrivKeyCertRequest(SignatureKeyCallback callback,
SignatureKeyCallback.PublicKeyBasedPrivKeyCertRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
//
// Signature verification
//
//
// Signature verification
//
/**
* Method that handles {@code SignatureVerificationKeyCallback}s. Called from {@code handleInternal()}.
* Default implementation delegates to specific handling methods.
*
* @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509CertificateRequest)
*/
protected final void handleSignatureVerificationKeyCallback(SignatureVerificationKeyCallback callback)
throws UnsupportedCallbackException, IOException {
if (callback.getRequest() instanceof SignatureVerificationKeyCallback.X509CertificateRequest) {
handleX509CertificateRequest(callback,
(SignatureVerificationKeyCallback.X509CertificateRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code SignatureVerificationKeyCallback}s. Called from {@code handleInternal()}.
* Default implementation delegates to specific handling methods.
*
* @see #handleX509CertificateRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509CertificateRequest)
*/
protected final void handleSignatureVerificationKeyCallback(SignatureVerificationKeyCallback callback)
throws UnsupportedCallbackException, IOException {
if (callback.getRequest() instanceof SignatureVerificationKeyCallback.X509CertificateRequest) {
handleX509CertificateRequest(callback,
(SignatureVerificationKeyCallback.X509CertificateRequest) callback.getRequest());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code SignatureVerificationKeyCallback}s with {@code X509CertificateRequest}s.
* Called from {@code handleSignatureVerificationKeyCallback()}. Default implementation delegates to specific
* handling methods.
*
* @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.PublicKeyBasedRequest)
* @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest)
* @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest)
*/
protected final void handleX509CertificateRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509CertificateRequest request)
throws UnsupportedCallbackException, IOException {
if (request instanceof SignatureVerificationKeyCallback.PublicKeyBasedRequest) {
handlePublicKeyBasedRequest(callback, (SignatureVerificationKeyCallback.PublicKeyBasedRequest) request);
}
else if (request instanceof SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) {
handleX509IssuerSerialBasedRequest(callback,
(SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) request);
}
else if (request instanceof SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
handleX509SubjectKeyIdentifierBasedRequest(callback,
(SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Method that handles {@code SignatureVerificationKeyCallback}s with {@code X509CertificateRequest}s.
* Called from {@code handleSignatureVerificationKeyCallback()}. Default implementation delegates to specific
* handling methods.
*
* @see #handlePublicKeyBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.PublicKeyBasedRequest)
* @see #handleX509IssuerSerialBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest)
* @see #handleX509SubjectKeyIdentifierBasedRequest(com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback,
* com.sun.xml.wss.impl.callback.SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest)
*/
protected final void handleX509CertificateRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509CertificateRequest request)
throws UnsupportedCallbackException, IOException {
if (request instanceof SignatureVerificationKeyCallback.PublicKeyBasedRequest) {
handlePublicKeyBasedRequest(callback, (SignatureVerificationKeyCallback.PublicKeyBasedRequest) request);
}
else if (request instanceof SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) {
handleX509IssuerSerialBasedRequest(callback,
(SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest) request);
}
else if (request instanceof SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) {
handleX509SubjectKeyIdentifierBasedRequest(callback,
(SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest) request);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedPrivKeyCertRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509SubjectKeyIdentifierBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509SubjectKeyIdentifierBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code X509IssuerSerialBasedRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code X509IssuerSerialBasedRequest}s.
* Called from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handleX509IssuerSerialBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.X509IssuerSerialBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedRequest}s. Called
* from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.PublicKeyBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
/**
* Template method that handles {@code SignatureKeyCallback}s with {@code PublicKeyBasedRequest}s. Called
* from {@code handlePrivKeyCertRequest()}. Default implementation throws an
* {@code UnsupportedCallbackException}.
*/
protected void handlePublicKeyBasedRequest(SignatureVerificationKeyCallback callback,
SignatureVerificationKeyCallback.PublicKeyBasedRequest request)
throws IOException, UnsupportedCallbackException {
throw new UnsupportedCallbackException(callback);
}
}

View File

@@ -33,101 +33,101 @@ import com.sun.xml.wss.impl.callback.TimestampValidationCallback;
*/
public class DefaultTimestampValidator implements TimestampValidationCallback.TimestampValidator {
@Override
public void validate(TimestampValidationCallback.Request request)
throws TimestampValidationCallback.TimestampValidationException {
if (request instanceof TimestampValidationCallback.UTCTimestampRequest) {
TimestampValidationCallback.UTCTimestampRequest utcRequest =
(TimestampValidationCallback.UTCTimestampRequest) request;
Date created = parseDate(utcRequest.getCreated());
@Override
public void validate(TimestampValidationCallback.Request request)
throws TimestampValidationCallback.TimestampValidationException {
if (request instanceof TimestampValidationCallback.UTCTimestampRequest) {
TimestampValidationCallback.UTCTimestampRequest utcRequest =
(TimestampValidationCallback.UTCTimestampRequest) request;
Date created = parseDate(utcRequest.getCreated());
validateCreationTime(created, utcRequest.getMaxClockSkew(), utcRequest.getTimestampFreshnessLimit());
validateCreationTime(created, utcRequest.getMaxClockSkew(), utcRequest.getTimestampFreshnessLimit());
if (utcRequest.getExpired() != null) {
Date expired = parseDate(utcRequest.getExpired());
validateExpirationTime(expired, utcRequest.getMaxClockSkew());
}
}
else {
throw new TimestampValidationCallback.TimestampValidationException("Unsupport request: [" + request + "]");
}
}
if (utcRequest.getExpired() != null) {
Date expired = parseDate(utcRequest.getExpired());
validateExpirationTime(expired, utcRequest.getMaxClockSkew());
}
}
else {
throw new TimestampValidationCallback.TimestampValidationException("Unsupport request: [" + request + "]");
}
}
private Date getFreshnessAndSkewAdjustedDate(long maxClockSkew, long timestampFreshnessLimit) {
Calendar c = new GregorianCalendar();
long offset = c.get(Calendar.ZONE_OFFSET);
if (c.getTimeZone().inDaylightTime(c.getTime())) {
offset += c.getTimeZone().getDSTSavings();
}
long beforeTime = c.getTimeInMillis();
long currentTime = beforeTime - offset;
private Date getFreshnessAndSkewAdjustedDate(long maxClockSkew, long timestampFreshnessLimit) {
Calendar c = new GregorianCalendar();
long offset = c.get(Calendar.ZONE_OFFSET);
if (c.getTimeZone().inDaylightTime(c.getTime())) {
offset += c.getTimeZone().getDSTSavings();
}
long beforeTime = c.getTimeInMillis();
long currentTime = beforeTime - offset;
long adjustedTime = currentTime - maxClockSkew - timestampFreshnessLimit;
c.setTimeInMillis(adjustedTime);
long adjustedTime = currentTime - maxClockSkew - timestampFreshnessLimit;
c.setTimeInMillis(adjustedTime);
return c.getTime();
}
return c.getTime();
}
private Date getGMTDateWithSkewAdjusted(Calendar calendar, long maxClockSkew, boolean addSkew) {
long offset = calendar.get(Calendar.ZONE_OFFSET);
if (calendar.getTimeZone().inDaylightTime(calendar.getTime())) {
offset += calendar.getTimeZone().getDSTSavings();
}
long beforeTime = calendar.getTimeInMillis();
long currentTime = beforeTime - offset;
private Date getGMTDateWithSkewAdjusted(Calendar calendar, long maxClockSkew, boolean addSkew) {
long offset = calendar.get(Calendar.ZONE_OFFSET);
if (calendar.getTimeZone().inDaylightTime(calendar.getTime())) {
offset += calendar.getTimeZone().getDSTSavings();
}
long beforeTime = calendar.getTimeInMillis();
long currentTime = beforeTime - offset;
if (addSkew) {
currentTime = currentTime + maxClockSkew;
}
else {
currentTime = currentTime - maxClockSkew;
}
if (addSkew) {
currentTime = currentTime + maxClockSkew;
}
else {
currentTime = currentTime - maxClockSkew;
}
calendar.setTimeInMillis(currentTime);
return calendar.getTime();
}
calendar.setTimeInMillis(currentTime);
return calendar.getTime();
}
private Date parseDate(String date) throws TimestampValidationCallback.TimestampValidationException {
SimpleDateFormat calendarFormatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat calendarFormatter2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
private Date parseDate(String date) throws TimestampValidationCallback.TimestampValidationException {
SimpleDateFormat calendarFormatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat calendarFormatter2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'");
try {
try {
return calendarFormatter1.parse(date);
}
catch (ParseException ignored) {
return calendarFormatter2.parse(date);
}
}
catch (ParseException ex) {
throw new TimestampValidationCallback.TimestampValidationException("Could not parse request date: " + date,
ex);
}
}
try {
try {
return calendarFormatter1.parse(date);
}
catch (ParseException ignored) {
return calendarFormatter2.parse(date);
}
}
catch (ParseException ex) {
throw new TimestampValidationCallback.TimestampValidationException("Could not parse request date: " + date,
ex);
}
}
private void validateCreationTime(Date created, long maxClockSkew, long timestampFreshnessLimit)
throws TimestampValidationCallback.TimestampValidationException {
Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew, timestampFreshnessLimit);
private void validateCreationTime(Date created, long maxClockSkew, long timestampFreshnessLimit)
throws TimestampValidationCallback.TimestampValidationException {
Date current = getFreshnessAndSkewAdjustedDate(maxClockSkew, timestampFreshnessLimit);
if (created.before(current)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The creation time is older than currenttime - timestamp-freshness-limit - max-clock-skew");
}
if (created.before(current)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The creation time is older than currenttime - timestamp-freshness-limit - max-clock-skew");
}
Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, true);
if (currentTime.before(created)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The creation time is ahead of the current time.");
}
}
Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, true);
if (currentTime.before(created)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The creation time is ahead of the current time.");
}
}
private void validateExpirationTime(Date expires, long maxClockSkew)
throws TimestampValidationCallback.TimestampValidationException {
Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, false);
if (expires.before(currentTime)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The current time is ahead of the expiration time in Timestamp");
}
}
private void validateExpirationTime(Date expires, long maxClockSkew)
throws TimestampValidationCallback.TimestampValidationException {
Date currentTime = getGMTDateWithSkewAdjusted(new GregorianCalendar(), maxClockSkew, false);
if (expires.before(currentTime)) {
throw new TimestampValidationCallback.TimestampValidationException(
"The current time is ahead of the expiration time in Timestamp");
}
}
}

View File

@@ -40,49 +40,49 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class MockValidationCallbackHandler extends AbstractCallbackHandler {
private boolean isValid = true;
private boolean isValid = true;
public MockValidationCallbackHandler() {
}
public MockValidationCallbackHandler() {
}
public MockValidationCallbackHandler(boolean valid) {
isValid = valid;
}
public MockValidationCallbackHandler(boolean valid) {
isValid = valid;
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback;
validationCallback.setValidator(new MockCertificateValidator());
}
else if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new MockPasswordValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback;
validationCallback.setValidator(new MockCertificateValidator());
}
else if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new MockPasswordValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
public void setValid(boolean valid) {
isValid = valid;
}
public void setValid(boolean valid) {
isValid = valid;
}
private class MockCertificateValidator implements CertificateValidationCallback.CertificateValidator {
private class MockCertificateValidator implements CertificateValidationCallback.CertificateValidator {
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
return isValid;
}
}
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
return isValid;
}
}
private class MockPasswordValidator implements PasswordValidationCallback.PasswordValidator {
private class MockPasswordValidator implements PasswordValidationCallback.PasswordValidator {
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
return isValid;
}
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
return isValid;
}
}
}

View File

@@ -43,59 +43,59 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class SimplePasswordValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean {
private Map<String, String> users = new HashMap<String, String>();
private Map<String, String> users = new HashMap<String, String>();
/** Sets the users to validate against. Property names are usernames, property values are passwords. */
public void setUsers(Properties users) {
for (Map.Entry<Object, Object> entry : users.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
this.users.put((String) entry.getKey(), (String) entry.getValue());
}
}
}
/** Sets the users to validate against. Property names are usernames, property values are passwords. */
public void setUsers(Properties users) {
for (Map.Entry<Object, Object> entry : users.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof String) {
this.users.put((String) entry.getKey(), (String) entry.getValue());
}
}
}
public void setUsersMap(Map<String, String> users) {
this.users = users;
}
public void setUsersMap(Map<String, String> users) {
this.users = users;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(users, "users is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(users, "users is required");
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback;
if (passwordCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
passwordCallback.setValidator(new SimplePlainTextPasswordValidator());
}
else if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest digestPasswordRequest =
(PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest();
String password = users.get(digestPasswordRequest.getUsername());
digestPasswordRequest.setPassword(password);
passwordCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback;
timestampCallback.setValidator(new DefaultTimestampValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback;
if (passwordCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
passwordCallback.setValidator(new SimplePlainTextPasswordValidator());
}
else if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest digestPasswordRequest =
(PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest();
String password = users.get(digestPasswordRequest.getUsername());
digestPasswordRequest.setPassword(password);
passwordCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback;
timestampCallback.setValidator(new DefaultTimestampValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
private class SimplePlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
private class SimplePlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextPasswordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
String password = users.get(plainTextPasswordRequest.getUsername());
return password != null && password.equals(plainTextPasswordRequest.getPassword());
}
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextPasswordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
String password = users.get(plainTextPasswordRequest.getUsername());
return password != null && password.equals(plainTextPasswordRequest.getPassword());
}
}
}

View File

@@ -40,51 +40,51 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class SimpleUsernamePasswordCallbackHandler extends AbstractCallbackHandler implements InitializingBean {
private String username;
private String username;
private String password;
private String password;
/**
* Constructs an empty instance of the {@code SimpleUsernamePasswordCallbackHandler}.
*/
public SimpleUsernamePasswordCallbackHandler() {
}
/**
* Constructs an empty instance of the {@code SimpleUsernamePasswordCallbackHandler}.
*/
public SimpleUsernamePasswordCallbackHandler() {
}
/**
* Constructs an instance of the {@code SimpleUsernamePasswordCallbackHandler} with the given name and password.
*/
public SimpleUsernamePasswordCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
/**
* Constructs an instance of the {@code SimpleUsernamePasswordCallbackHandler} with the given name and password.
*/
public SimpleUsernamePasswordCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasLength(username, "username must be set");
Assert.hasLength(password, "password must be set");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasLength(username, "username must be set");
Assert.hasLength(password, "password must be set");
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof UsernameCallback) {
UsernameCallback usernameCallback = (UsernameCallback) callback;
usernameCallback.setUsername(username);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword(password);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof UsernameCallback) {
UsernameCallback usernameCallback = (UsernameCallback) callback;
usernameCallback.setUsername(username);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword(password);
}
else {
throw new UnsupportedCallbackException(callback);
}
}
}

View File

@@ -53,69 +53,69 @@ import org.springframework.ws.soap.security.x509.X509AuthenticationToken;
*/
public class SpringCertificateValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean {
private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
private boolean ignoreFailure = false;
private boolean ignoreFailure = false;
/** Sets the Spring Security authentication manager. Required. */
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/** Sets the Spring Security authentication manager. Required. */
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void setIgnoreFailure(boolean ignoreFailure) {
this.ignoreFailure = ignoreFailure;
}
public void setIgnoreFailure(boolean ignoreFailure) {
this.ignoreFailure = ignoreFailure;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "authenticationManager is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "authenticationManager is required");
}
/**
* Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for
* others
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
((CertificateValidationCallback) callback).setValidator(new SpringSecurityCertificateValidator());
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for
* others
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
((CertificateValidationCallback) callback).setValidator(new SpringSecurityCertificateValidator());
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
}
else {
throw new UnsupportedCallbackException(callback);
}
}
private class SpringSecurityCertificateValidator implements CertificateValidationCallback.CertificateValidator {
private class SpringSecurityCertificateValidator implements CertificateValidationCallback.CertificateValidator {
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
boolean result;
try {
Authentication authResult =
authenticationManager.authenticate(new X509AuthenticationToken(certificate));
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] successful");
}
SecurityContextHolder.getContext().setAuthentication(authResult);
return true;
}
catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed: " + failed.toString());
}
SecurityContextHolder.clearContext();
result = ignoreFailure;
}
return result;
}
}
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
boolean result;
try {
Authentication authResult =
authenticationManager.authenticate(new X509AuthenticationToken(certificate));
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] successful");
}
SecurityContextHolder.getContext().setAuthentication(authResult);
return true;
}
catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed: " + failed.toString());
}
SecurityContextHolder.clearContext();
result = ignoreFailure;
}
return result;
}
}
}

View File

@@ -55,105 +55,105 @@ import org.springframework.ws.soap.security.support.SpringSecurityUtils;
*/
public class SpringDigestPasswordValidationCallbackHandler extends AbstractCallbackHandler implements InitializingBean {
private UserCache userCache = new NullUserCache();
private UserCache userCache = new NullUserCache();
private UserDetailsService userDetailsService;
private UserDetailsService userDetailsService;
/** Sets the users cache. Not required, but can benefit performance. */
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
/** Sets the users cache. Not required, but can benefit performance. */
public void setUserCache(UserCache userCache) {
this.userCache = userCache;
}
/** Sets the Spring Security user details service. Required. */
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/** Sets the Spring Security user details service. Required. */
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "userDetailsService is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(userDetailsService, "userDetailsService is required");
}
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code DigestPasswordRequest}, and throws an
* {@code UnsupportedCallbackException} for others
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback;
if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest request =
(PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest();
String username = request.getUsername();
UserDetails user = loadUserDetails(username);
if (user != null) {
SpringSecurityUtils.checkUserValidity(user);
request.setPassword(user.getPassword());
}
SpringSecurityDigestPasswordValidator validator = new SpringSecurityDigestPasswordValidator(user);
passwordCallback.setValidator(validator);
return;
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback;
timestampCallback.setValidator(new DefaultTimestampValidator());
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code DigestPasswordRequest}, and throws an
* {@code UnsupportedCallbackException} for others
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback passwordCallback = (PasswordValidationCallback) callback;
if (passwordCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest request =
(PasswordValidationCallback.DigestPasswordRequest) passwordCallback.getRequest();
String username = request.getUsername();
UserDetails user = loadUserDetails(username);
if (user != null) {
SpringSecurityUtils.checkUserValidity(user);
request.setPassword(user.getPassword());
}
SpringSecurityDigestPasswordValidator validator = new SpringSecurityDigestPasswordValidator(user);
passwordCallback.setValidator(validator);
return;
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback timestampCallback = (TimestampValidationCallback) callback;
timestampCallback.setValidator(new DefaultTimestampValidator());
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
return;
}
throw new UnsupportedCallbackException(callback);
}
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
return;
}
throw new UnsupportedCallbackException(callback);
}
private UserDetails loadUserDetails(String username) throws DataAccessException {
UserDetails user = userCache.getUserFromCache(username);
private UserDetails loadUserDetails(String username) throws DataAccessException {
UserDetails user = userCache.getUserFromCache(username);
if (user == null) {
try {
user = userDetailsService.loadUserByUsername(username);
}
catch (UsernameNotFoundException notFound) {
if (logger.isDebugEnabled()) {
logger.debug("Username '" + username + "' not found");
}
return null;
}
userCache.putUserInCache(user);
}
return user;
}
if (user == null) {
try {
user = userDetailsService.loadUserByUsername(username);
}
catch (UsernameNotFoundException notFound) {
if (logger.isDebugEnabled()) {
logger.debug("Username '" + username + "' not found");
}
return null;
}
userCache.putUserInCache(user);
}
return user;
}
private class SpringSecurityDigestPasswordValidator extends PasswordValidationCallback.DigestPasswordValidator {
private class SpringSecurityDigestPasswordValidator extends PasswordValidationCallback.DigestPasswordValidator {
private UserDetails user;
private UserDetails user;
private SpringSecurityDigestPasswordValidator(UserDetails user) {
this.user = user;
}
private SpringSecurityDigestPasswordValidator(UserDetails user) {
this.user = user;
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
if (super.validate(request)) {
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(user, user.getPassword());
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authRequest.toString());
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
if (super.validate(request)) {
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(user, user.getPassword());
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authRequest.toString());
}
SecurityContextHolder.getContext().setAuthentication(authRequest);
return true;
}
else {
return false;
}
}
}
SecurityContextHolder.getContext().setAuthentication(authRequest);
return true;
}
else {
return false;
}
}
}
}

View File

@@ -50,74 +50,74 @@ import org.springframework.ws.soap.security.callback.CleanupCallback;
* @since 1.5.0
*/
public class SpringPlainTextPasswordValidationCallbackHandler extends AbstractCallbackHandler
implements InitializingBean {
implements InitializingBean {
private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
private boolean ignoreFailure = false;
private boolean ignoreFailure = false;
/** Sets the Spring Security authentication manager. Required. */
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/** Sets the Spring Security authentication manager. Required. */
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public void setIgnoreFailure(boolean ignoreFailure) {
this.ignoreFailure = ignoreFailure;
}
public void setIgnoreFailure(boolean ignoreFailure) {
this.ignoreFailure = ignoreFailure;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "authenticationManager is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(authenticationManager, "authenticationManager is required");
}
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws
* an {@code UnsupportedCallbackException} for others.
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
validationCallback.setValidator(new SpringSecurityPlainTextPasswordValidator());
return;
}
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
return;
}
throw new UnsupportedCallbackException(callback);
}
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws
* an {@code UnsupportedCallbackException} for others.
*
* @throws javax.security.auth.callback.UnsupportedCallbackException
* when the callback is not supported
*/
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
validationCallback.setValidator(new SpringSecurityPlainTextPasswordValidator());
return;
}
}
else if (callback instanceof CleanupCallback) {
SecurityContextHolder.clearContext();
return;
}
throw new UnsupportedCallbackException(callback);
}
private class SpringSecurityPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
private class SpringSecurityPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
try {
Authentication authResult = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
plainTextRequest.getUsername(), plainTextRequest.getPassword()));
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult.toString());
}
SecurityContextHolder.getContext().setAuthentication(authResult);
return true;
}
catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + plainTextRequest.getUsername() + "' failed: " +
failed.toString());
}
SecurityContextHolder.clearContext();
return ignoreFailure;
}
}
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
try {
Authentication authResult = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
plainTextRequest.getUsername(), plainTextRequest.getPassword()));
if (logger.isDebugEnabled()) {
logger.debug("Authentication success: " + authResult.toString());
}
SecurityContextHolder.getContext().setAuthentication(authResult);
return true;
}
catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + plainTextRequest.getUsername() + "' failed: " +
failed.toString());
}
SecurityContextHolder.clearContext();
return ignoreFailure;
}
}
}
}

View File

@@ -39,32 +39,32 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class SpringUsernamePasswordCallbackHandler extends AbstractCallbackHandler {
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof UsernameCallback) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getName() != null) {
UsernameCallback usernameCallback = (UsernameCallback) callback;
usernameCallback.setUsername(authentication.getName());
return;
}
else {
logger.warn(
"Cannot handle UsernameCallback: Spring Security SecurityContext contains no Authentication");
}
}
else if (callback instanceof PasswordCallback) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getName() != null) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword(authentication.getCredentials().toString());
return;
}
else {
logger.warn(
"Canot handle PasswordCallback: Spring Security SecurityContext contains no Authentication");
}
}
throw new UnsupportedCallbackException(callback);
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof UsernameCallback) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getName() != null) {
UsernameCallback usernameCallback = (UsernameCallback) callback;
usernameCallback.setUsername(authentication.getName());
return;
}
else {
logger.warn(
"Cannot handle UsernameCallback: Spring Security SecurityContext contains no Authentication");
}
}
else if (callback instanceof PasswordCallback) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getName() != null) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword(authentication.getCredentials().toString());
return;
}
else {
logger.warn(
"Canot handle PasswordCallback: Spring Security SecurityContext contains no Authentication");
}
}
throw new UnsupportedCallbackException(callback);
}
}

View File

@@ -37,126 +37,126 @@ import org.springframework.ws.soap.security.callback.CallbackHandlerChain;
*/
public class XwssCallbackHandlerChain extends CallbackHandlerChain {
public XwssCallbackHandlerChain(CallbackHandler[] callbackHandlers) {
super(callbackHandlers);
}
public XwssCallbackHandlerChain(CallbackHandler[] callbackHandlers) {
super(callbackHandlers);
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
handleCertificateValidationCallback((CertificateValidationCallback) callback);
}
else if (callback instanceof PasswordValidationCallback) {
handlePasswordValidationCallback((PasswordValidationCallback) callback);
}
else if (callback instanceof TimestampValidationCallback) {
handleTimestampValidationCallback((TimestampValidationCallback) callback);
}
else {
super.handleInternal(callback);
}
}
@Override
protected void handleInternal(Callback callback) throws IOException, UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
handleCertificateValidationCallback((CertificateValidationCallback) callback);
}
else if (callback instanceof PasswordValidationCallback) {
handlePasswordValidationCallback((PasswordValidationCallback) callback);
}
else if (callback instanceof TimestampValidationCallback) {
handleTimestampValidationCallback((TimestampValidationCallback) callback);
}
else {
super.handleInternal(callback);
}
}
private void handleCertificateValidationCallback(CertificateValidationCallback callback) {
callback.setValidator(new CertificateValidatorChain(callback));
}
private void handleCertificateValidationCallback(CertificateValidationCallback callback) {
callback.setValidator(new CertificateValidatorChain(callback));
}
private void handlePasswordValidationCallback(PasswordValidationCallback callback) {
callback.setValidator(new PasswordValidatorChain(callback));
}
private void handlePasswordValidationCallback(PasswordValidationCallback callback) {
callback.setValidator(new PasswordValidatorChain(callback));
}
private void handleTimestampValidationCallback(TimestampValidationCallback callback) {
callback.setValidator(new TimestampValidatorChain(callback));
}
private void handleTimestampValidationCallback(TimestampValidationCallback callback) {
callback.setValidator(new TimestampValidatorChain(callback));
}
private class TimestampValidatorChain implements TimestampValidationCallback.TimestampValidator {
private class TimestampValidatorChain implements TimestampValidationCallback.TimestampValidator {
private TimestampValidationCallback callback;
private TimestampValidationCallback callback;
private TimestampValidatorChain(TimestampValidationCallback callback) {
this.callback = callback;
}
private TimestampValidatorChain(TimestampValidationCallback callback) {
this.callback = callback;
}
@Override
public void validate(TimestampValidationCallback.Request request)
throws TimestampValidationCallback.TimestampValidationException {
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
callback.getResult();
}
catch (IOException e) {
throw new TimestampValidationCallback.TimestampValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
}
}
@Override
public void validate(TimestampValidationCallback.Request request)
throws TimestampValidationCallback.TimestampValidationException {
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
callback.getResult();
}
catch (IOException e) {
throw new TimestampValidationCallback.TimestampValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
}
}
private class PasswordValidatorChain implements PasswordValidationCallback.PasswordValidator {
private class PasswordValidatorChain implements PasswordValidationCallback.PasswordValidator {
private PasswordValidationCallback callback;
private PasswordValidationCallback callback;
private PasswordValidatorChain(PasswordValidationCallback callback) {
this.callback = callback;
}
private PasswordValidatorChain(PasswordValidationCallback callback) {
this.callback = callback;
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
boolean allUnsupported = true;
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
if (!callback.getResult()) {
return false;
}
}
catch (IOException e) {
throw new PasswordValidationCallback.PasswordValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
return !allUnsupported;
}
}
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
boolean allUnsupported = true;
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
if (!callback.getResult()) {
return false;
}
}
catch (IOException e) {
throw new PasswordValidationCallback.PasswordValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
return !allUnsupported;
}
}
private class CertificateValidatorChain implements CertificateValidationCallback.CertificateValidator {
private class CertificateValidatorChain implements CertificateValidationCallback.CertificateValidator {
private CertificateValidationCallback callback;
private CertificateValidationCallback callback;
private CertificateValidatorChain(CertificateValidationCallback callback) {
this.callback = callback;
}
private CertificateValidatorChain(CertificateValidationCallback callback) {
this.callback = callback;
}
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
boolean allUnsupported = true;
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
if (!callback.getResult()) {
return false;
}
}
catch (IOException e) {
throw new CertificateValidationCallback.CertificateValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
return !allUnsupported;
}
}
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
boolean allUnsupported = true;
for (int i = 0; i < getCallbackHandlers().length; i++) {
CallbackHandler callbackHandler = getCallbackHandlers()[i];
try {
callbackHandler.handle(new Callback[]{callback});
allUnsupported = false;
if (!callback.getResult()) {
return false;
}
}
catch (IOException e) {
throw new CertificateValidationCallback.CertificateValidationException(e);
}
catch (UnsupportedCallbackException e) {
// ignore
}
}
return !allUnsupported;
}
}
}

View File

@@ -27,25 +27,25 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
* @since 1.0.0
*/
public abstract class AbstractJaasValidationCallbackHandler extends AbstractCallbackHandler
implements InitializingBean {
implements InitializingBean {
private String loginContextName;
private String loginContextName;
protected AbstractJaasValidationCallbackHandler() {
}
protected AbstractJaasValidationCallbackHandler() {
}
/** Returns the login context name. */
public String getLoginContextName() {
return loginContextName;
}
/** Returns the login context name. */
public String getLoginContextName() {
return loginContextName;
}
/** Sets the login context name. */
public void setLoginContextName(String loginContextName) {
this.loginContextName = loginContextName;
}
/** Sets the login context name. */
public void setLoginContextName(String loginContextName) {
this.loginContextName = loginContextName;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(loginContextName, "loginContextName is required");
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(loginContextName, "loginContextName is required");
}
}

View File

@@ -39,65 +39,65 @@ import com.sun.xml.wss.impl.callback.CertificateValidationCallback;
*/
public class JaasCertificateValidationCallbackHandler extends AbstractJaasValidationCallbackHandler {
/**
* Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for
* others
*
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
((CertificateValidationCallback) callback).setValidator(new JaasCertificateValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
/**
* Handles {@code CertificateValidationCallback}s, and throws an {@code UnsupportedCallbackException} for
* others
*
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof CertificateValidationCallback) {
((CertificateValidationCallback) callback).setValidator(new JaasCertificateValidator());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
private class JaasCertificateValidator implements CertificateValidationCallback.CertificateValidator {
private class JaasCertificateValidator implements CertificateValidationCallback.CertificateValidator {
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
Subject subject = new Subject();
subject.getPrincipals().add(certificate.getSubjectX500Principal());
LoginContext loginContext;
try {
loginContext = new LoginContext(getLoginContextName(), subject);
}
catch (LoginException ex) {
throw new CertificateValidationCallback.CertificateValidationException(ex);
}
catch (SecurityException ex) {
throw new CertificateValidationCallback.CertificateValidationException(ex);
}
@Override
public boolean validate(X509Certificate certificate)
throws CertificateValidationCallback.CertificateValidationException {
Subject subject = new Subject();
subject.getPrincipals().add(certificate.getSubjectX500Principal());
LoginContext loginContext;
try {
loginContext = new LoginContext(getLoginContextName(), subject);
}
catch (LoginException ex) {
throw new CertificateValidationCallback.CertificateValidationException(ex);
}
catch (SecurityException ex) {
throw new CertificateValidationCallback.CertificateValidationException(ex);
}
try {
loginContext.login();
Subject subj = loginContext.getSubject();
if (!subj.getPrincipals().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] successful");
}
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed");
}
return false;
}
}
catch (LoginException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed");
}
return false;
}
}
}
try {
loginContext.login();
Subject subj = loginContext.getSubject();
if (!subj.getPrincipals().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] successful");
}
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed");
}
return false;
}
}
catch (LoginException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for certificate with DN [" +
certificate.getSubjectX500Principal().getName() + "] failed");
}
return false;
}
}
}
}

View File

@@ -40,85 +40,85 @@ import org.springframework.ws.soap.security.callback.AbstractCallbackHandler;
*/
public class JaasPlainTextPasswordValidationCallbackHandler extends AbstractJaasValidationCallbackHandler {
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws
* an {@code UnsupportedCallbackException} for others.
*
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
validationCallback.setValidator(new JaasPlainTextPasswordValidator());
return;
}
}
throw new UnsupportedCallbackException(callback);
}
/**
* Handles {@code PasswordValidationCallback}s that contain a {@code PlainTextPasswordRequest}, and throws
* an {@code UnsupportedCallbackException} for others.
*
* @throws UnsupportedCallbackException when the callback is not supported
*/
@Override
protected final void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
validationCallback.setValidator(new JaasPlainTextPasswordValidator());
return;
}
}
throw new UnsupportedCallbackException(callback);
}
private class JaasPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
private class JaasPlainTextPasswordValidator implements PasswordValidationCallback.PasswordValidator {
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
@Override
public boolean validate(PasswordValidationCallback.Request request)
throws PasswordValidationCallback.PasswordValidationException {
PasswordValidationCallback.PlainTextPasswordRequest plainTextRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
final String username = plainTextRequest.getUsername();
final String password = plainTextRequest.getPassword();
final String username = plainTextRequest.getUsername();
final String password = plainTextRequest.getPassword();
LoginContext loginContext;
try {
loginContext = new LoginContext(getLoginContextName(), new AbstractCallbackHandler() {
LoginContext loginContext;
try {
loginContext = new LoginContext(getLoginContextName(), new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
}
else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
});
}
catch (LoginException ex) {
throw new PasswordValidationCallback.PasswordValidationException(ex);
}
catch (SecurityException ex) {
throw new PasswordValidationCallback.PasswordValidationException(ex);
}
@Override
protected void handleInternal(Callback callback) throws UnsupportedCallbackException {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
}
else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback);
}
}
});
}
catch (LoginException ex) {
throw new PasswordValidationCallback.PasswordValidationException(ex);
}
catch (SecurityException ex) {
throw new PasswordValidationCallback.PasswordValidationException(ex);
}
try {
loginContext.login();
Subject subject = loginContext.getSubject();
if (!subject.getPrincipals().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' successful");
}
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' failed");
}
return false;
}
}
catch (LoginException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' failed");
}
return false;
}
}
try {
loginContext.login();
Subject subject = loginContext.getSubject();
if (!subject.getPrincipals().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' successful");
}
return true;
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' failed");
}
return false;
}
}
catch (LoginException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user '" + username + "' failed");
}
return false;
}
}
}
}
}

View File

@@ -24,35 +24,35 @@ import org.junit.Test;
public class CallbackHandlerChainTest {
private CallbackHandler supported = new CallbackHandler() {
public void handle(Callback[] callbacks) {
}
};
private CallbackHandler supported = new CallbackHandler() {
public void handle(Callback[] callbacks) {
}
};
private CallbackHandler unsupported = new CallbackHandler() {
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
throw new UnsupportedCallbackException(callbacks[0]);
}
};
private CallbackHandler unsupported = new CallbackHandler() {
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
throw new UnsupportedCallbackException(callbacks[0]);
}
};
private Callback callback = new Callback() {
};
private Callback callback = new Callback() {
};
@Test
public void testSupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{supported});
chain.handle(new Callback[]{callback});
}
@Test
public void testSupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{supported});
chain.handle(new Callback[]{callback});
}
@Test
public void testUnsupportedSupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported, supported});
chain.handle(new Callback[]{callback});
}
@Test
public void testUnsupportedSupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported, supported});
chain.handle(new Callback[]{callback});
}
@Test(expected = UnsupportedCallbackException.class)
public void testUnsupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported});
chain.handle(new Callback[]{callback});
}
@Test(expected = UnsupportedCallbackException.class)
public void testUnsupported() throws Exception {
CallbackHandlerChain chain = new CallbackHandlerChain(new CallbackHandler[]{unsupported});
chain.handle(new Callback[]{callback});
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,

View File

@@ -17,6 +17,6 @@
package org.springframework.ws.soap.security.wss4j;
public class AxiomWss4jMessageInterceptorSpringSecurityCallbackHandlerTest
extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase {
extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase {
}

View File

@@ -17,6 +17,6 @@
package org.springframework.ws.soap.security.wss4j;
public class AxiomWss4jMessageInterceptorUsernameTokenSignatureTest
extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase {
extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase {
}

View File

@@ -41,43 +41,43 @@ import static org.junit.Assert.assertTrue;
public class SaajWss4jMessageInterceptorSignTest extends Wss4jMessageInterceptorSignTestCase {
private static final String PAYLOAD =
"<tru:StockSymbol xmlns:tru=\"http://fabrikam123.com/payloads\">QQQ</tru:StockSymbol>";
private static final String PAYLOAD =
"<tru:StockSymbol xmlns:tru=\"http://fabrikam123.com/payloads\">QQQ</tru:StockSymbol>";
@Test
public void testSignAndValidate() throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SOAPMessage saajMessage = saajSoap11MessageFactory.createMessage();
transformer.transform(new StringSource(PAYLOAD), new DOMResult(saajMessage.getSOAPBody()));
SoapMessage message = new SaajSoapMessage(saajMessage, saajSoap11MessageFactory);
MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory));
@Test
public void testSignAndValidate() throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SOAPMessage saajMessage = saajSoap11MessageFactory.createMessage();
transformer.transform(new StringSource(PAYLOAD), new DOMResult(saajMessage.getSOAPBody()));
SoapMessage message = new SaajSoapMessage(saajMessage, saajSoap11MessageFactory);
MessageContext messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory));
interceptor.secureMessage(message, messageContext);
interceptor.secureMessage(message, messageContext);
SOAPHeader header = ((SaajSoapMessage) message).getSaajMessage().getSOAPHeader();
Iterator<?> iterator = header.getChildElements(new QName(
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security"));
assertTrue("No security header", iterator.hasNext());
SOAPHeaderElement securityHeader = (SOAPHeaderElement) iterator.next();
iterator = securityHeader.getChildElements(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"));
assertTrue("No signature header", iterator.hasNext());
SOAPHeader header = ((SaajSoapMessage) message).getSaajMessage().getSOAPHeader();
Iterator<?> iterator = header.getChildElements(new QName(
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security"));
assertTrue("No security header", iterator.hasNext());
SOAPHeaderElement securityHeader = (SOAPHeaderElement) iterator.next();
iterator = securityHeader.getChildElements(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"));
assertTrue("No signature header", iterator.hasNext());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
message.writeTo(bos);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
message.writeTo(bos);
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
SOAPMessage signed = saajSoap11MessageFactory.createMessage(mimeHeaders, bis);
message = new SaajSoapMessage(signed, saajSoap11MessageFactory);
messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory));
SOAPMessage signed = saajSoap11MessageFactory.createMessage(mimeHeaders, bis);
message = new SaajSoapMessage(signed, saajSoap11MessageFactory);
messageContext = new DefaultMessageContext(message, new SaajSoapMessageFactory(saajSoap11MessageFactory));
interceptor.validateMessage(message, messageContext);
}
interceptor.validateMessage(message, messageContext);
}
}

View File

@@ -17,6 +17,6 @@
package org.springframework.ws.soap.security.wss4j;
public class SaajWss4jMessageInterceptorSpringSecurityCallbackHandlerTest
extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase {
extends Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase {
}

View File

@@ -17,6 +17,6 @@
package org.springframework.ws.soap.security.wss4j;
public class SaajWss4jMessageInterceptorUsernameTokenSignatureTest
extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase {
extends Wss4jMessageInterceptorUsernameTokenSignatureTestCase {
}

View File

@@ -29,56 +29,56 @@ import static org.junit.Assert.fail;
public abstract class Wss4jInterceptorTestCase extends Wss4jTestCase {
@Test
public void testHandleRequest() throws Exception {
SoapMessage request = loadSoap11Message("empty-soap.xml");
final Object requestMessage = getMessage(request);
SoapMessage validatedRequest = loadSoap11Message("empty-soap.xml");
final Object validatedRequestMessage = getMessage(validatedRequest);
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException {
fail("secure not expected");
}
@Test
public void testHandleRequest() throws Exception {
SoapMessage request = loadSoap11Message("empty-soap.xml");
final Object requestMessage = getMessage(request);
SoapMessage validatedRequest = loadSoap11Message("empty-soap.xml");
final Object validatedRequestMessage = getMessage(validatedRequest);
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException {
fail("secure not expected");
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
assertEquals("Invalid message", requestMessage, getMessage(soapMessage));
setMessage(soapMessage, validatedRequestMessage);
}
};
MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory());
interceptor.handleRequest(context, null);
assertEquals("Invalid request", validatedRequestMessage, getMessage((SoapMessage) context.getRequest()));
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
assertEquals("Invalid message", requestMessage, getMessage(soapMessage));
setMessage(soapMessage, validatedRequestMessage);
}
};
MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory());
interceptor.handleRequest(context, null);
assertEquals("Invalid request", validatedRequestMessage, getMessage((SoapMessage) context.getRequest()));
}
@Test
public void testHandleResponse() throws Exception {
SoapMessage securedResponse = loadSoap11Message("empty-soap.xml");
final Object securedResponseMessage = getMessage(securedResponse);
@Test
public void testHandleResponse() throws Exception {
SoapMessage securedResponse = loadSoap11Message("empty-soap.xml");
final Object securedResponseMessage = getMessage(securedResponse);
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException {
setMessage(soapMessage, securedResponseMessage);
}
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecuritySecurementException {
setMessage(soapMessage, securedResponseMessage);
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
};
SoapMessage request = loadSoap11Message("empty-soap.xml");
MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory());
context.getResponse();
interceptor.handleResponse(context, null);
assertEquals("Invalid response", securedResponseMessage, getMessage((SoapMessage) context.getResponse()));
}
};
SoapMessage request = loadSoap11Message("empty-soap.xml");
MessageContext context = new DefaultMessageContext(request, getSoap11MessageFactory());
context.getResponse();
interceptor.handleResponse(context, null);
assertEquals("Invalid response", securedResponseMessage, getMessage((SoapMessage) context.getResponse()));
}
}

View File

@@ -29,58 +29,58 @@ import org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean;
public abstract class Wss4jMessageInterceptorEncryptionTestCase extends Wss4jTestCase {
protected Wss4jSecurityInterceptor interceptor;
protected Wss4jSecurityInterceptor interceptor;
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Encrypt");
interceptor.setSecurementActions("Encrypt");
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Encrypt");
interceptor.setSecurementActions("Encrypt");
KeyStoreCallbackHandler callbackHandler = new KeyStoreCallbackHandler();
callbackHandler.setPrivateKeyPassword("123456");
interceptor.setValidationCallbackHandler(callbackHandler);
KeyStoreCallbackHandler callbackHandler = new KeyStoreCallbackHandler();
callbackHandler.setPrivateKeyPassword("123456");
interceptor.setValidationCallbackHandler(callbackHandler);
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
Properties cryptoFactoryBeanConfig = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
Properties cryptoFactoryBeanConfig = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean.afterPropertiesSet();
interceptor.setValidationDecryptionCrypto(cryptoFactoryBean
.getObject());
interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean
.getObject());
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean.afterPropertiesSet();
interceptor.setValidationDecryptionCrypto(cryptoFactoryBean
.getObject());
interceptor.setSecurementEncryptionCrypto(cryptoFactoryBean
.getObject());
interceptor.afterPropertiesSet();
}
interceptor.afterPropertiesSet();
}
@Test
public void testDecryptRequest() throws Exception {
SoapMessage message = loadSoap11Message("encrypted-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Document document = getDocument((SoapMessage) messageContext.getRequest());
assertXpathEvaluatesTo("Decryption error", "Hello", "/SOAP-ENV:Envelope/SOAP-ENV:Body/echo:echoRequest/text()",
document);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
@Test
public void testDecryptRequest() throws Exception {
SoapMessage message = loadSoap11Message("encrypted-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Document document = getDocument((SoapMessage) messageContext.getRequest());
assertXpathEvaluatesTo("Decryption error", "Hello", "/SOAP-ENV:Envelope/SOAP-ENV:Body/echo:echoRequest/text()",
document);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
@Test
public void testEncryptResponse() throws Exception {
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setSecurementEncryptionUser("rsakey");
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
assertXpathExists("Encryption error", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey",
document);
}
@Test
public void testEncryptResponse() throws Exception {
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setSecurementEncryptionUser("rsakey");
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
assertXpathExists("Encryption error", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey",
document);
}
}

View File

@@ -39,122 +39,122 @@ import org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidat
*/
public abstract class Wss4jMessageInterceptorHeaderTestCase extends Wss4jTestCase {
private Wss4jSecurityInterceptor interceptor;
private Wss4jSecurityInterceptor interceptorThatKeepsSecurityHeader;
private Wss4jSecurityInterceptor interceptor;
private Wss4jSecurityInterceptor interceptorThatKeepsSecurityHeader;
@Override
protected void onSetup() throws Exception {
Properties users = new Properties();
users.setProperty("Bert", "Ernie");
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidateRequest(true);
interceptor.setSecureResponse(true);
interceptor.setValidationActions("UsernameToken");
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
@Override
protected void onSetup() throws Exception {
Properties users = new Properties();
users.setProperty("Bert", "Ernie");
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidateRequest(true);
interceptor.setSecureResponse(true);
interceptor.setValidationActions("UsernameToken");
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
interceptorThatKeepsSecurityHeader = new Wss4jSecurityInterceptor();
interceptorThatKeepsSecurityHeader.setValidateRequest(true);
interceptorThatKeepsSecurityHeader.setSecureResponse(true);
interceptorThatKeepsSecurityHeader.setValidationActions("UsernameToken");
interceptorThatKeepsSecurityHeader.setValidationCallbackHandler(callbackHandler);
interceptorThatKeepsSecurityHeader.setRemoveSecurityHeader(false);
interceptorThatKeepsSecurityHeader.afterPropertiesSet();
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
interceptorThatKeepsSecurityHeader = new Wss4jSecurityInterceptor();
interceptorThatKeepsSecurityHeader.setValidateRequest(true);
interceptorThatKeepsSecurityHeader.setSecureResponse(true);
interceptorThatKeepsSecurityHeader.setValidationActions("UsernameToken");
interceptorThatKeepsSecurityHeader.setValidationCallbackHandler(callbackHandler);
interceptorThatKeepsSecurityHeader.setRemoveSecurityHeader(false);
interceptorThatKeepsSecurityHeader.afterPropertiesSet();
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
for (Iterator<SoapHeaderElement> i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) {
SoapHeaderElement element = i.next();
QName name = element.getName();
if (name.getNamespaceURI()
.equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) {
fail("Security Header not removed");
}
for (Iterator<SoapHeaderElement> i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) {
SoapHeaderElement element = i.next();
QName name = element.getName();
if (name.getNamespaceURI()
.equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) {
fail("Security Header not removed");
}
}
}
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message));
assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message));
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message));
assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message));
}
}
@Test
public void testValidateUsernameTokenPlainTextButKeepSecurityHeader() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptorThatKeepsSecurityHeader.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
@Test
public void testValidateUsernameTokenPlainTextButKeepSecurityHeader() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainTextWithHeaders-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptorThatKeepsSecurityHeader.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
boolean foundSecurityHeader = false;
for (Iterator<SoapHeaderElement> i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) {
SoapHeaderElement element = i.next();
QName name = element.getName();
if (name.getNamespaceURI()
.equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) {
foundSecurityHeader = true;
}
boolean foundSecurityHeader = false;
for (Iterator<SoapHeaderElement> i = message.getEnvelope().getHeader().examineAllHeaderElements(); i.hasNext();) {
SoapHeaderElement element = i.next();
QName name = element.getName();
if (name.getNamespaceURI()
.equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")) {
foundSecurityHeader = true;
}
}
assertTrue(foundSecurityHeader);
}
assertTrue(foundSecurityHeader);
assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message));
assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message));
assertXpathExists("header1 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header1", getDocument(message));
assertXpathExists("header2 not found", "/SOAP-ENV:Envelope/SOAP-ENV:Header/header2", getDocument(message));
}
}
@Test(expected=WsSecurityValidationException.class)
public void testEmptySecurityHeader() throws Exception {
SoapMessage message = loadSoap11Message("emptySecurityHeader-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
}
@Test
public void testPreserveCustomHeaders() throws Exception {
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
@Test(expected=WsSecurityValidationException.class)
public void testEmptySecurityHeader() throws Exception {
SoapMessage message = loadSoap11Message("emptySecurityHeader-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
}
@Test
public void testPreserveCustomHeaders() throws Exception {
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
ByteArrayOutputStream os = new ByteArrayOutputStream();
SoapMessage message = loadSoap11Message("customHeader-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
message.writeTo(os);
String document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathNotExists("Header 2 exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", document);
ByteArrayOutputStream os = new ByteArrayOutputStream();
SoapMessage message = loadSoap11Message("customHeader-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
message.writeTo(os);
String document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathNotExists("Header 2 exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2", document);
interceptor.secureMessage(message, messageContext);
interceptor.secureMessage(message, messageContext);
SoapHeaderElement element = message.getSoapHeader().addHeaderElement(new QName("http://test", "header2"));
element.setText("test2");
SoapHeaderElement element = message.getSoapHeader().addHeaderElement(new QName("http://test", "header2"));
element.setText("test2");
os = new ByteArrayOutputStream();
message.writeTo(os);
document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2",
document);
os = new ByteArrayOutputStream();
message.writeTo(os);
document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2",
document);
os = new ByteArrayOutputStream();
message.writeTo(os);
document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2",
document);
}
os = new ByteArrayOutputStream();
message.writeTo(os);
document = os.toString("UTF-8");
assertXpathEvaluatesTo("Header 1 does not exist", "test1", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header1",
document);
assertXpathEvaluatesTo("Header 2 does not exist", "test2", "/SOAP-ENV:Envelope/SOAP-ENV:Header/test:header2",
document);
}
}

View File

@@ -31,93 +31,93 @@ import static org.junit.Assert.assertNotNull;
public abstract class Wss4jMessageInterceptorSignTestCase extends Wss4jTestCase {
protected Wss4jSecurityInterceptor interceptor;
protected Wss4jSecurityInterceptor interceptor;
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Signature");
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Signature");
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
Properties cryptoFactoryBeanConfig = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
Properties cryptoFactoryBeanConfig = new Properties();
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean.afterPropertiesSet();
interceptor.setValidationSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.setSecurementSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.afterPropertiesSet();
// from the class path
cryptoFactoryBeanConfig.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
cryptoFactoryBean.setConfiguration(cryptoFactoryBeanConfig);
cryptoFactoryBean.afterPropertiesSet();
interceptor.setValidationSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.setSecurementSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.afterPropertiesSet();
}
}
@Test
public void testValidateCertificate() throws Exception {
SoapMessage message = loadSoap11Message("signed-soap.xml");
@Test
public void testValidateCertificate() throws Exception {
SoapMessage message = loadSoap11Message("signed-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
@Test
public void testValidateCertificateWithSignatureConfirmation() throws Exception {
SoapMessage message = loadSoap11Message("signed-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setEnableSignatureConfirmation(true);
interceptor.validateMessage(message, messageContext);
WebServiceMessage response = messageContext.getResponse();
interceptor.secureMessage(message, messageContext);
assertNotNull("No result returned", response);
Document document = getDocument((SoapMessage) response);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse11:SignatureConfirmation", document);
}
@Test
public void testValidateCertificateWithSignatureConfirmation() throws Exception {
SoapMessage message = loadSoap11Message("signed-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setEnableSignatureConfirmation(true);
interceptor.validateMessage(message, messageContext);
WebServiceMessage response = messageContext.getResponse();
interceptor.secureMessage(message, messageContext);
assertNotNull("No result returned", response);
Document document = getDocument((SoapMessage) response);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse11:SignatureConfirmation", document);
}
@Test
public void testSignResponse() throws Exception {
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
@Test
public void testSignResponse() throws Exception {
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
// interceptor.setSecurementSignatureKeyIdentifier("IssuerSerial");
// interceptor.setSecurementSignatureKeyIdentifier("IssuerSerial");
interceptor.secureMessage(message, messageContext);
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document);
Document document = getDocument(message);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document);
}
}
@Test
public void testSignResponseWithSignatureUser() throws Exception {
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementSignatureUser("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
@Test
public void testSignResponseWithSignatureUser() throws Exception {
interceptor.setSecurementActions("Signature");
interceptor.setEnableSignatureConfirmation(false);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementSignatureUser("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document);
Document document = getDocument(message);
assertXpathExists("Absent SignatureConfirmation element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature", document);
}
}
}

View File

@@ -32,77 +32,77 @@ import static org.junit.Assert.assertNotNull;
public abstract class Wss4jMessageInterceptorSoapActionTestCase extends Wss4jTestCase {
private static final String SOAP_ACTION = "\"http://test\"";
private static final String SOAP_ACTION = "\"http://test\"";
private Properties users;
private Properties users;
private Wss4jSecurityInterceptor interceptor;
private Wss4jSecurityInterceptor interceptor;
@Override
protected void onSetup() throws Exception {
users = new Properties();
users.setProperty("Bert", "Ernie");
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("UsernameToken");
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
interceptor.setValidationCallbackHandler(callbackHandler);
@Override
protected void onSetup() throws Exception {
users = new Properties();
users.setProperty("Bert", "Ernie");
interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("UsernameToken");
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
}
interceptor.afterPropertiesSet();
}
@Test
public void testPreserveSoapActionOnValidation() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
message.setSoapAction(SOAP_ACTION);
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
@Test
public void testPreserveSoapActionOnValidation() throws Exception {
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
message.setSoapAction(SOAP_ACTION);
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
@Test
public void testPreserveSoap12ActionOnValidation() throws Exception {
SoapMessage message = loadSoap12Message("usernameTokenPlainText-soap12.xml");
message.setSoapAction(SOAP_ACTION);
WebServiceMessageFactory messageFactory = getSoap12MessageFactory();
MessageContext messageContext = new DefaultMessageContext(message, messageFactory);
interceptor.validateMessage(message, messageContext);
@Test
public void testPreserveSoap12ActionOnValidation() throws Exception {
SoapMessage message = loadSoap12Message("usernameTokenPlainText-soap12.xml");
message.setSoapAction(SOAP_ACTION);
WebServiceMessageFactory messageFactory = getSoap12MessageFactory();
MessageContext messageContext = new DefaultMessageContext(message, messageFactory);
interceptor.validateMessage(message, messageContext);
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
@Test
public void testPreserveSoapActionOnSecurement() throws Exception {
SoapMessage message = loadSoap11Message("empty-soap.xml");
message.setSoapAction(SOAP_ACTION);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
@Test
public void testPreserveSoapActionOnSecurement() throws Exception {
SoapMessage message = loadSoap11Message("empty-soap.xml");
message.setSoapAction(SOAP_ACTION);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
}
@Test
public void testPreserveSoap12ActionOnSecurement() throws Exception {
SoapMessage message = loadSoap12Message("empty-soap12.xml");
message.setSoapAction(SOAP_ACTION);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
MessageContext messageContext = getSoap12MessageContext(message);
interceptor.secureMessage(message, messageContext);
@Test
public void testPreserveSoap12ActionOnSecurement() throws Exception {
SoapMessage message = loadSoap12Message("empty-soap12.xml");
message.setSoapAction(SOAP_ACTION);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
MessageContext messageContext = getSoap12MessageContext(message);
interceptor.secureMessage(message, messageContext);
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
assertNotNull("Soap Action must not be null", message.getSoapAction());
assertEquals("Soap Action is different from expected", SOAP_ACTION, message.getSoapAction());
}
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -37,91 +37,91 @@ import static org.junit.Assert.assertNull;
public abstract class Wss4jMessageInterceptorSpringSecurityCallbackHandlerTestCase extends Wss4jTestCase {
private Properties users = new Properties();
private Properties users = new Properties();
private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
@Override
protected void onSetup() throws Exception {
authenticationManager = createMock(AuthenticationManager.class);
users.setProperty("Bert", "Ernie,ROLE_TEST");
}
@Override
protected void onSetup() throws Exception {
authenticationManager = createMock(AuthenticationManager.class);
users.setProperty("Bert", "Ernie,ROLE_TEST");
}
@After
public void tearDown() throws Exception {
verify(authenticationManager);
SecurityContextHolder.clearContext();
}
@After
public void tearDown() throws Exception {
verify(authenticationManager);
SecurityContextHolder.clearContext();
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
EndpointInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext, null);
assertValidateUsernameToken(message);
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
EndpointInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext, null);
assertValidateUsernameToken(message);
// test clean up
messageContext.getResponse();
interceptor.handleResponse(messageContext, null);
interceptor.afterCompletion(messageContext, null, null);
assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
// test clean up
messageContext.getResponse();
interceptor.handleResponse(messageContext, null);
interceptor.afterCompletion(messageContext, null, null);
assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
@Test
public void testValidateUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
@Test
public void testValidateUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext);
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext);
interceptor = prepareInterceptor("UsernameToken", true, true);
interceptor.handleRequest(messageContext, null);
assertValidateUsernameToken(message);
interceptor = prepareInterceptor("UsernameToken", true, true);
interceptor.handleRequest(messageContext, null);
assertValidateUsernameToken(message);
// test clean up
messageContext.getResponse();
interceptor.handleResponse(messageContext, null);
interceptor.afterCompletion(messageContext, null, null);
assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
// test clean up
messageContext.getResponse();
interceptor.handleResponse(messageContext, null);
interceptor.afterCompletion(messageContext, null, null);
assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
protected void assertValidateUsernameToken(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
protected void assertValidateUsernameToken(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest)
throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
if (validating) {
interceptor.setValidationActions(actions);
}
else {
interceptor.setSecurementActions(actions);
}
SpringSecurityPasswordValidationCallbackHandler callbackHandler =
new SpringSecurityPasswordValidationCallbackHandler();
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(users);
callbackHandler.setUserDetailsService(userDetailsManager);
if (digest) {
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
}
else {
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
}
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
replay(authenticationManager);
return interceptor;
}
protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest)
throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
if (validating) {
interceptor.setValidationActions(actions);
}
else {
interceptor.setSecurementActions(actions);
}
SpringSecurityPasswordValidationCallbackHandler callbackHandler =
new SpringSecurityPasswordValidationCallbackHandler();
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(users);
callbackHandler.setUserDetailsService(userDetailsManager);
if (digest) {
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
}
else {
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
}
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
replay(authenticationManager);
return interceptor;
}
}

View File

@@ -31,73 +31,73 @@ import static org.junit.Assert.assertEquals;
public abstract class Wss4jMessageInterceptorTimestampTestCase extends Wss4jTestCase {
@Test
public void testAddTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
Document document = getDocument(message);
assertXpathExists("timestamp header not found",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp", document);
}
@Test
public void testAddTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
Document document = getDocument(message);
assertXpathExists("timestamp header not found",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp", document);
}
@Test
public void testValidateTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = getMessageWithTimestamp();
@Test
public void testValidateTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = getMessageWithTimestamp();
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, context);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, context);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
@Test(expected = WsSecurityValidationException.class)
public void testValidateTimestampWithExpiredTtl() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("expiredTimestamp-soap.xml");
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, context);
}
@Test(expected = WsSecurityValidationException.class)
public void testValidateTimestampWithExpiredTtl() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setValidationActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("expiredTimestamp-soap.xml");
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, context);
}
@Test
public void testSecureTimestampWithCustomTtl() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.setTimestampStrict(true);
int ttlInSeconds = 1;
interceptor.setSecurementTimeToLive(ttlInSeconds);
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.secureMessage(message, context);
String created = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Created/text()",
message.getEnvelope().getSource());
String expires = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Expires/text()",
message.getEnvelope().getSource());
@Test
public void testSecureTimestampWithCustomTtl() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.setTimestampStrict(true);
int ttlInSeconds = 1;
interceptor.setSecurementTimeToLive(ttlInSeconds);
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.secureMessage(message, context);
String created = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Created/text()",
message.getEnvelope().getSource());
String expires = xpathTemplate.evaluateAsString("/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsu:Timestamp/wsu:Expires/text()",
message.getEnvelope().getSource());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
long actualTtl = format.parse(expires).getTime() - format.parse(created).getTime();
assertEquals("invalid ttl", 1000 * ttlInSeconds, actualTtl);
}
long actualTtl = format.parse(expires).getTime() - format.parse(created).getTime();
assertEquals("invalid ttl", 1000 * ttlInSeconds, actualTtl);
}
private SoapMessage getMessageWithTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
return message;
}
private SoapMessage getMessageWithTimestamp() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Timestamp");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
return message;
}
}

View File

@@ -24,22 +24,22 @@ import org.w3c.dom.Document;
public abstract class Wss4jMessageInterceptorUsernameTokenSignatureTestCase extends Wss4jTestCase {
@Test
public void testAddUsernameTokenSignature() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameTokenSignature");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
@Test
public void testAddUsernameTokenSignature() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameTokenSignature");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.afterPropertiesSet();
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext context = getSoap11MessageContext(message);
interceptor.secureMessage(message, context);
Document doc = getDocument(message);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathExists("Invalid Password",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']/text()",
doc);
}
Document doc = getDocument(message);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathExists("Invalid Password",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']/text()",
doc);
}
}

View File

@@ -31,122 +31,122 @@ import static org.junit.Assert.assertNotNull;
public abstract class Wss4jMessageInterceptorUsernameTokenTestCase extends Wss4jTestCase {
private Properties users = new Properties();
private Properties users = new Properties();
@Override
protected void onSetup() throws Exception {
users.setProperty("Bert", "Ernie");
}
@Override
protected void onSetup() throws Exception {
users.setProperty("Bert", "Ernie");
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainText-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
@Test
public void testValidateUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
@Test
public void testValidateUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("UsernameToken");
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext);
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.handleRequest(messageContext);
interceptor = prepareInterceptor("UsernameToken", true, true);
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
interceptor = prepareInterceptor("UsernameToken", true, true);
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
@Test
public void testValidateUsernameTokenWithQualifiedType() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainTextQualifiedType-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
@Test
public void testValidateUsernameTokenWithQualifiedType() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", true, false);
SoapMessage message = loadSoap11Message("usernameTokenPlainTextQualifiedType-soap.xml");
MessageContext messageContext = new DefaultMessageContext(message, getSoap11MessageFactory());
interceptor.validateMessage(message, messageContext);
assertValidateUsernameToken(message);
}
@Test
public void testAddUsernameTokenPlainText() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, false);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
SoapMessage message = loadSoap11Message("empty-soap.xml");
@Test
public void testAddUsernameTokenPlainText() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, false);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
assertAddUsernameTokenPlainText(message);
}
interceptor.secureMessage(message, messageContext);
assertAddUsernameTokenPlainText(message);
}
@Test
public void testAddUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, true);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
SoapMessage message = loadSoap11Message("empty-soap.xml");
@Test
public void testAddUsernameTokenDigest() throws Exception {
Wss4jSecurityInterceptor interceptor = prepareInterceptor("UsernameToken", false, true);
interceptor.setSecurementUsername("Bert");
interceptor.setSecurementPassword("Ernie");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
assertAddUsernameTokenDigest(message);
}
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.secureMessage(message, messageContext);
assertAddUsernameTokenDigest(message);
}
protected void assertValidateUsernameToken(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
protected void assertValidateUsernameToken(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security",
getDocument(message));
}
protected void assertAddUsernameTokenPlainText(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
Document doc = getDocument(message);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
doc);
}
protected void assertAddUsernameTokenPlainText(SoapMessage message) throws Exception {
Object result = getMessage(message);
assertNotNull("No result returned", result);
Document doc = getDocument(message);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
doc);
}
protected void assertAddUsernameTokenDigest(SoapMessage message) throws Exception {
Object result = getMessage(message);
Document doc = getDocument(message);
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathExists("Password does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']",
doc);
protected void assertAddUsernameTokenDigest(SoapMessage message) throws Exception {
Object result = getMessage(message);
Document doc = getDocument(message);
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", doc);
assertXpathExists("Password does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']",
doc);
}
}
protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest)
throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
if (validating) {
interceptor.setValidationActions(actions);
}
else {
interceptor.setSecurementActions(actions);
}
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
if (digest) {
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
}
else {
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
}
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
return interceptor;
}
protected Wss4jSecurityInterceptor prepareInterceptor(String actions, boolean validating, boolean digest)
throws Exception {
Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
if (validating) {
interceptor.setValidationActions(actions);
}
else {
interceptor.setSecurementActions(actions);
}
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsers(users);
if (digest) {
interceptor.setSecurementPasswordType(WSConstants.PW_DIGEST);
}
else {
interceptor.setSecurementPasswordType(WSConstants.PW_TEXT);
}
interceptor.setValidationCallbackHandler(callbackHandler);
interceptor.afterPropertiesSet();
return interceptor;
}
}

View File

@@ -27,46 +27,46 @@ import org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean;
public abstract class Wss4jMessageInterceptorX509TestCase extends Wss4jTestCase {
protected Wss4jSecurityInterceptor interceptor;
protected Wss4jSecurityInterceptor interceptor;
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Signature");
interceptor.setValidationActions("Signature");
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
cryptoFactoryBean.setCryptoProvider(Merlin.class);
cryptoFactoryBean.setKeyStoreType("jceks");
cryptoFactoryBean.setKeyStorePassword("123456");
cryptoFactoryBean.setKeyStoreLocation(new ClassPathResource("private.jks"));
@Override
protected void onSetup() throws Exception {
interceptor = new Wss4jSecurityInterceptor();
interceptor.setSecurementActions("Signature");
interceptor.setValidationActions("Signature");
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
cryptoFactoryBean.setCryptoProvider(Merlin.class);
cryptoFactoryBean.setKeyStoreType("jceks");
cryptoFactoryBean.setKeyStorePassword("123456");
cryptoFactoryBean.setKeyStoreLocation(new ClassPathResource("private.jks"));
cryptoFactoryBean.afterPropertiesSet();
interceptor.setSecurementSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.setValidationSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.afterPropertiesSet();
cryptoFactoryBean.afterPropertiesSet();
interceptor.setSecurementSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.setValidationSignatureCrypto(cryptoFactoryBean
.getObject());
interceptor.afterPropertiesSet();
}
}
@Test
public void testAddCertificate() throws Exception {
@Test
public void testAddCertificate() throws Exception {
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setSecurementPassword("123456");
interceptor.setSecurementUsername("rsaKey");
SoapMessage message = loadSoap11Message("empty-soap.xml");
MessageContext messageContext = getSoap11MessageContext(message);
interceptor.setSecurementSignatureKeyIdentifier("DirectReference");
interceptor.setSecurementSignatureKeyIdentifier("DirectReference");
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
interceptor.secureMessage(message, messageContext);
Document document = getDocument(message);
assertXpathExists("Absent BinarySecurityToken element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", document);
assertXpathExists("Absent BinarySecurityToken element",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", document);
// lets verify the signature that we've just generated
interceptor.validateMessage(message, messageContext);
}
// lets verify the signature that we've just generated
interceptor.validateMessage(message, messageContext);
}
}

View File

@@ -54,228 +54,228 @@ import static org.junit.Assert.assertTrue;
public abstract class Wss4jTestCase {
protected MessageFactory saajSoap11MessageFactory;
protected MessageFactory saajSoap11MessageFactory;
protected MessageFactory saajSoap12MessageFactory;
protected MessageFactory saajSoap12MessageFactory;
protected final boolean axiomTest = this.getClass().getSimpleName().startsWith("Axiom");
protected final boolean axiomTest = this.getClass().getSimpleName().startsWith("Axiom");
protected final boolean saajTest = this.getClass().getSimpleName().startsWith("Saaj");
protected final boolean saajTest = this.getClass().getSimpleName().startsWith("Saaj");
protected Jaxp13XPathTemplate xpathTemplate = new Jaxp13XPathTemplate();
protected Jaxp13XPathTemplate xpathTemplate = new Jaxp13XPathTemplate();
@Before
public final void setUp() throws Exception {
if (!axiomTest && !saajTest) {
throw new IllegalArgumentException("test class name must start with either Axiom or Saaj");
}
saajSoap11MessageFactory = MessageFactory.newInstance();
saajSoap12MessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
namespaces.put("wsse",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#");
namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#");
namespaces.put("wsse11", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd");
namespaces.put("echo", "http://www.springframework.org/spring-ws/samples/echo");
namespaces.put("wsu",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
namespaces.put("test", "http://test");
xpathTemplate.setNamespaces(namespaces);
onSetup();
}
@Before
public final void setUp() throws Exception {
if (!axiomTest && !saajTest) {
throw new IllegalArgumentException("test class name must start with either Axiom or Saaj");
}
saajSoap11MessageFactory = MessageFactory.newInstance();
saajSoap12MessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
namespaces.put("wsse",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#");
namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#");
namespaces.put("wsse11", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd");
namespaces.put("echo", "http://www.springframework.org/spring-ws/samples/echo");
namespaces.put("wsu",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
namespaces.put("test", "http://test");
xpathTemplate.setNamespaces(namespaces);
onSetup();
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
Document document) {
String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new DOMSource(document));
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
Document document) {
String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new DOMSource(document));
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
String document) {
String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new StringSource(document));
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
String document) {
String actualValue = xpathTemplate.evaluateAsString(xpathExpression, new StringSource(document));
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathExists(String message, String xpathExpression, Document document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document));
Assert.assertNotNull(message, node);
}
protected void assertXpathExists(String message, String xpathExpression, Document document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document));
Assert.assertNotNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, Document document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document));
Assert.assertNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, Document document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new DOMSource(document));
Assert.assertNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, String document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new StringSource(document));
Assert.assertNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, String document) {
Node node = xpathTemplate.evaluateAsNode(xpathExpression, new StringSource(document));
Assert.assertNull(message, node);
}
protected SaajSoapMessage loadSaaj11Message(String fileName) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(saajSoap11MessageFactory.createMessage(mimeHeaders, is), saajSoap11MessageFactory);
}
finally {
is.close();
}
}
protected SaajSoapMessage loadSaaj12Message(String fileName) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "application/soap+xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(saajSoap12MessageFactory.createMessage(mimeHeaders, is), saajSoap12MessageFactory);
}
finally {
is.close();
}
}
protected SaajSoapMessage loadSaaj11Message(String fileName) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(saajSoap11MessageFactory.createMessage(mimeHeaders, is), saajSoap11MessageFactory);
}
finally {
is.close();
}
}
protected SaajSoapMessage loadSaaj12Message(String fileName) throws Exception {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "application/soap+xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(saajSoap12MessageFactory.createMessage(mimeHeaders, is), saajSoap12MessageFactory);
}
finally {
is.close();
}
}
protected AxiomSoapMessage loadAxiom11Message(String fileName) throws Exception {
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load Axiom message [" + resource + "]", resource.exists());
is = resource.getInputStream();
protected AxiomSoapMessage loadAxiom11Message(String fileName) throws Exception {
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load Axiom message [" + resource + "]", resource.exists());
is = resource.getInputStream();
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, null);
org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage();
return new AxiomSoapMessage(soapMessage, "", true, true);
}
finally {
is.close();
}
}
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, null);
org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage();
return new AxiomSoapMessage(soapMessage, "", true, true);
}
finally {
is.close();
}
}
@SuppressWarnings("Since15")
protected AxiomSoapMessage loadAxiom12Message(String fileName) throws Exception {
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load Axiom message [" + resource + "]", resource.exists());
is = resource.getInputStream();
@SuppressWarnings("Since15")
protected AxiomSoapMessage loadAxiom12Message(String fileName) throws Exception {
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load Axiom message [" + resource + "]", resource.exists());
is = resource.getInputStream();
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage();
return new AxiomSoapMessage(soapMessage, "", true, true);
}
finally {
is.close();
}
}
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(is);
StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(parser, SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
org.apache.axiom.soap.SOAPMessage soapMessage = builder.getSoapMessage();
return new AxiomSoapMessage(soapMessage, "", true, true);
}
finally {
is.close();
}
}
protected Object getMessage(SoapMessage soapMessage) {
if (soapMessage instanceof SaajSoapMessage) {
return ((SaajSoapMessage) soapMessage).getSaajMessage();
}
if (soapMessage instanceof AxiomSoapMessage) {
return ((AxiomSoapMessage) soapMessage).getAxiomMessage();
protected Object getMessage(SoapMessage soapMessage) {
if (soapMessage instanceof SaajSoapMessage) {
return ((SaajSoapMessage) soapMessage).getSaajMessage();
}
if (soapMessage instanceof AxiomSoapMessage) {
return ((AxiomSoapMessage) soapMessage).getAxiomMessage();
}
throw new IllegalArgumentException("Illegal message: " + soapMessage);
}
}
throw new IllegalArgumentException("Illegal message: " + soapMessage);
}
protected void setMessage(SoapMessage soapMessage, Object message) {
if (soapMessage instanceof SaajSoapMessage) {
((SaajSoapMessage) soapMessage).setSaajMessage((SOAPMessage) message);
return;
}
if (soapMessage instanceof AxiomSoapMessage) {
((AxiomSoapMessage) soapMessage).setAxiomMessage((org.apache.axiom.soap.SOAPMessage) message);
return;
}
throw new IllegalArgumentException("Illegal message: " + message);
}
protected void setMessage(SoapMessage soapMessage, Object message) {
if (soapMessage instanceof SaajSoapMessage) {
((SaajSoapMessage) soapMessage).setSaajMessage((SOAPMessage) message);
return;
}
if (soapMessage instanceof AxiomSoapMessage) {
((AxiomSoapMessage) soapMessage).setAxiomMessage((org.apache.axiom.soap.SOAPMessage) message);
return;
}
throw new IllegalArgumentException("Illegal message: " + message);
}
protected void onSetup() throws Exception {
}
protected void onSetup() throws Exception {
}
protected SoapMessage loadSoap11Message(String fileName) throws Exception {
if (axiomTest) {
return loadAxiom11Message(fileName);
}
if (saajTest) {
return loadSaaj11Message(fileName);
}
throw new IllegalArgumentException();
}
protected SoapMessage loadSoap11Message(String fileName) throws Exception {
if (axiomTest) {
return loadAxiom11Message(fileName);
}
if (saajTest) {
return loadSaaj11Message(fileName);
}
throw new IllegalArgumentException();
}
protected SoapMessage loadSoap12Message(String fileName) throws Exception {
if (axiomTest) {
return loadAxiom12Message(fileName);
}
if (saajTest) {
return loadSaaj12Message(fileName);
}
throw new IllegalArgumentException();
}
protected SoapMessage loadSoap12Message(String fileName) throws Exception {
if (axiomTest) {
return loadAxiom12Message(fileName);
}
if (saajTest) {
return loadSaaj12Message(fileName);
}
throw new IllegalArgumentException();
}
protected SoapMessageFactory getSoap11MessageFactory() throws Exception {
if (axiomTest) {
return new AxiomSoapMessageFactory();
}
if (saajTest) {
return new SaajSoapMessageFactory(saajSoap11MessageFactory);
}
throw new IllegalArgumentException();
}
protected SoapMessageFactory getSoap11MessageFactory() throws Exception {
if (axiomTest) {
return new AxiomSoapMessageFactory();
}
if (saajTest) {
return new SaajSoapMessageFactory(saajSoap11MessageFactory);
}
throw new IllegalArgumentException();
}
protected SoapMessageFactory getSoap12MessageFactory() throws Exception {
SoapMessageFactory messageFactory;
if (axiomTest) {
messageFactory = new AxiomSoapMessageFactory();
} else if (saajTest) {
messageFactory = new SaajSoapMessageFactory(saajSoap12MessageFactory);
} else
throw new IllegalArgumentException();
messageFactory.setSoapVersion(SoapVersion.SOAP_12);
return messageFactory;
}
protected Document getDocument(SoapMessage message) throws Exception {
if (axiomTest) {
return AxiomUtils.toDocument(((AxiomSoapMessage) message).getAxiomMessage().getSOAPEnvelope());
}
if (saajTest) {
return ((SaajSoapMessage) message).getSaajMessage().getSOAPPart();
}
throw new IllegalArgumentException();
}
protected SoapMessageFactory getSoap12MessageFactory() throws Exception {
SoapMessageFactory messageFactory;
if (axiomTest) {
messageFactory = new AxiomSoapMessageFactory();
} else if (saajTest) {
messageFactory = new SaajSoapMessageFactory(saajSoap12MessageFactory);
} else
throw new IllegalArgumentException();
messageFactory.setSoapVersion(SoapVersion.SOAP_12);
return messageFactory;
}
protected Document getDocument(SoapMessage message) throws Exception {
if (axiomTest) {
return AxiomUtils.toDocument(((AxiomSoapMessage) message).getAxiomMessage().getSOAPEnvelope());
}
if (saajTest) {
return ((SaajSoapMessage) message).getSaajMessage().getSOAPPart();
}
throw new IllegalArgumentException();
}
protected MessageContext getSoap11MessageContext(final SoapMessage response) throws Exception {
return new DefaultMessageContext(response, getSoap11MessageFactory()) {
@Override
public WebServiceMessage getResponse() {
return response;
}
};
}
protected MessageContext getSoap11MessageContext(final SoapMessage response) throws Exception {
return new DefaultMessageContext(response, getSoap11MessageFactory()) {
@Override
public WebServiceMessage getResponse() {
return response;
}
};
}
protected MessageContext getSoap12MessageContext(final SoapMessage response) throws Exception {
return new DefaultMessageContext(response, getSoap12MessageFactory()) {
@Override
public WebServiceMessage getResponse() {
return response;
}
};
}
protected MessageContext getSoap12MessageContext(final SoapMessage response) throws Exception {
return new DefaultMessageContext(response, getSoap12MessageFactory()) {
@Override
public WebServiceMessage getResponse() {
return response;
}
};
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -28,29 +28,29 @@ import org.junit.Test;
public class KeyStoreCallbackHandlerTest {
private KeyStoreCallbackHandler callbackHandler;
private KeyStoreCallbackHandler callbackHandler;
private WSPasswordCallback callback;
private WSPasswordCallback callback;
@Before
public void setUp() throws Exception {
callbackHandler = new KeyStoreCallbackHandler();
callback = new WSPasswordCallback("secretkey", WSPasswordCallback.SECRET_KEY);
@Before
public void setUp() throws Exception {
callbackHandler = new KeyStoreCallbackHandler();
callback = new WSPasswordCallback("secretkey", WSPasswordCallback.SECRET_KEY);
KeyStoreFactoryBean factory = new KeyStoreFactoryBean();
factory.setLocation(new ClassPathResource("private.jks"));
factory.setPassword("123456");
factory.setType("JCEKS");
factory.afterPropertiesSet();
KeyStore keyStore = factory.getObject();
callbackHandler.setKeyStore(keyStore);
callbackHandler.setSymmetricKeyPassword("123456");
}
KeyStoreFactoryBean factory = new KeyStoreFactoryBean();
factory.setLocation(new ClassPathResource("private.jks"));
factory.setPassword("123456");
factory.setType("JCEKS");
factory.afterPropertiesSet();
KeyStore keyStore = factory.getObject();
callbackHandler.setKeyStore(keyStore);
callbackHandler.setSymmetricKeyPassword("123456");
}
@Test
public void testHandleKeyName() throws Exception {
callbackHandler.handleInternal(callback);
Assert.assertNotNull("symmetric key must not be null", callback.getKey());
}
@Test
public void testHandleKeyName() throws Exception {
callbackHandler.handleInternal(callback);
Assert.assertNotNull("symmetric key must not be null", callback.getKey());
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -38,44 +38,44 @@ import static org.easymock.EasyMock.*;
/** @author tareq */
public class SpringSecurityPasswordValidationCallbackHandlerTest {
private SpringSecurityPasswordValidationCallbackHandler callbackHandler;
private SpringSecurityPasswordValidationCallbackHandler callbackHandler;
private SimpleGrantedAuthority grantedAuthority;
private SimpleGrantedAuthority grantedAuthority;
private UsernameTokenPrincipalCallback callback;
private UsernameTokenPrincipalCallback callback;
private UserDetails user;
private UserDetails user;
@Before
public void setUp() throws Exception {
callbackHandler = new SpringSecurityPasswordValidationCallbackHandler();
@Before
public void setUp() throws Exception {
callbackHandler = new SpringSecurityPasswordValidationCallbackHandler();
grantedAuthority = new SimpleGrantedAuthority("ROLE_1");
user = new User("Ernie", "Bert", true, true, true, true, Collections.singleton(grantedAuthority));
grantedAuthority = new SimpleGrantedAuthority("ROLE_1");
user = new User("Ernie", "Bert", true, true, true, true, Collections.singleton(grantedAuthority));
WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal("Ernie", true);
callback = new UsernameTokenPrincipalCallback(principal);
}
WSUsernameTokenPrincipal principal = new WSUsernameTokenPrincipal("Ernie", true);
callback = new UsernameTokenPrincipalCallback(principal);
}
@Test
public void testHandleUsernameTokenPrincipal() throws Exception {
UserDetailsService userDetailsService = createMock(UserDetailsService.class);
callbackHandler.setUserDetailsService(userDetailsService);
@Test
public void testHandleUsernameTokenPrincipal() throws Exception {
UserDetailsService userDetailsService = createMock(UserDetailsService.class);
callbackHandler.setUserDetailsService(userDetailsService);
expect(userDetailsService.loadUserByUsername("Ernie")).andReturn(user).anyTimes();
expect(userDetailsService.loadUserByUsername("Ernie")).andReturn(user).anyTimes();
replay(userDetailsService);
replay(userDetailsService);
callbackHandler.handleUsernameTokenPrincipal(callback);
SecurityContext context = SecurityContextHolder.getContext();
Assert.assertNotNull("SecurityContext must not be null", context);
Authentication authentication = context.getAuthentication();
Assert.assertNotNull("Authentication must not be null", authentication);
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
Assert.assertTrue("GrantedAuthority[] must not be null or empty",
(authorities != null && authorities.size() > 0));
Assert.assertEquals("Unexpected authority", grantedAuthority, authorities.iterator().next());
callbackHandler.handleUsernameTokenPrincipal(callback);
SecurityContext context = SecurityContextHolder.getContext();
Assert.assertNotNull("SecurityContext must not be null", context);
Authentication authentication = context.getAuthentication();
Assert.assertNotNull("Authentication must not be null", authentication);
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
Assert.assertTrue("GrantedAuthority[] must not be null or empty",
(authorities != null && authorities.size() > 0));
Assert.assertEquals("Unexpected authority", grantedAuthority, authorities.iterator().next());
verify(userDetailsService);
}
verify(userDetailsService);
}
}

View File

@@ -28,40 +28,40 @@ import org.junit.Test;
public class CryptoFactoryBeanTest {
private CryptoFactoryBean factoryBean;
private CryptoFactoryBean factoryBean;
@Before
public void setUp() throws Exception {
factoryBean = new CryptoFactoryBean();
}
@Before
public void setUp() throws Exception {
factoryBean = new CryptoFactoryBean();
}
@Test
public void testSetConfiguration() throws Exception {
Properties configuration = new Properties();
configuration.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
configuration.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
@Test
public void testSetConfiguration() throws Exception {
Properties configuration = new Properties();
configuration.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.type", "jceks");
configuration.setProperty("org.apache.ws.security.crypto.merlin.keystore.password", "123456");
configuration.setProperty("org.apache.ws.security.crypto.merlin.file", "private.jks");
factoryBean.setConfiguration(configuration);
factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
factoryBean.afterPropertiesSet();
factoryBean.setConfiguration(configuration);
factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
factoryBean.afterPropertiesSet();
Object result = factoryBean.getObject();
Assert.assertNotNull("No result", result);
Assert.assertTrue("Not a Merlin instance", result instanceof Merlin);
}
Object result = factoryBean.getObject();
Assert.assertNotNull("No result", result);
Assert.assertTrue("Not a Merlin instance", result instanceof Merlin);
}
@Test
public void testProperties() throws Exception {
factoryBean.setKeyStoreType("jceks");
factoryBean.setKeyStorePassword("123456");
factoryBean.setKeyStoreLocation(new ClassPathResource("private.jks"));
factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
factoryBean.afterPropertiesSet();
Object result = factoryBean.getObject();
Assert.assertNotNull("No result", result);
Assert.assertTrue("Not a Merlin instance", result instanceof Merlin);
}
@Test
public void testProperties() throws Exception {
factoryBean.setKeyStoreType("jceks");
factoryBean.setKeyStorePassword("123456");
factoryBean.setKeyStoreLocation(new ClassPathResource("private.jks"));
factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
factoryBean.afterPropertiesSet();
Object result = factoryBean.getObject();
Assert.assertNotNull("No result", result);
Assert.assertTrue("Not a Merlin instance", result instanceof Merlin);
}
}

View File

@@ -23,26 +23,26 @@ import java.security.cert.X509Certificate;
public abstract class AbstractXwssMessageInterceptorKeyStoreTestCase extends AbstractXwssMessageInterceptorTestCase {
protected X509Certificate certificate;
protected X509Certificate certificate;
protected PrivateKey privateKey;
protected PrivateKey privateKey;
@Override
protected void onSetup() throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = getClass().getResourceAsStream("test-keystore.jks");
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
certificate = (X509Certificate) keyStore.getCertificate("alias");
privateKey = (PrivateKey) keyStore.getKey("alias", "password".toCharArray());
@Override
protected void onSetup() throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = getClass().getResourceAsStream("test-keystore.jks");
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
certificate = (X509Certificate) keyStore.getCertificate("alias");
privateKey = (PrivateKey) keyStore.getKey("alias", "password".toCharArray());
}
}
}

View File

@@ -40,64 +40,64 @@ import static org.junit.Assert.assertTrue;
public abstract class AbstractXwssMessageInterceptorTestCase {
protected XwsSecurityInterceptor interceptor;
protected XwsSecurityInterceptor interceptor;
private MessageFactory messageFactory;
private MessageFactory messageFactory;
private Map<String, String> namespaces;
private Map<String, String> namespaces;
@Before
public final void setUp() throws Exception {
interceptor = new XwsSecurityInterceptor();
messageFactory = MessageFactory.newInstance();
namespaces = new HashMap<String, String>(4);
namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
namespaces.put("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
namespaces.put("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#");
namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#");
onSetup();
}
@Before
public final void setUp() throws Exception {
interceptor = new XwsSecurityInterceptor();
messageFactory = MessageFactory.newInstance();
namespaces = new HashMap<String, String>(4);
namespaces.put("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/");
namespaces.put("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
namespaces.put("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
namespaces.put("ds", "http://www.w3.org/2000/09/xmldsig#");
namespaces.put("xenc", "http://www.w3.org/2001/04/xmlenc#");
onSetup();
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
String actualValue = expression.evaluateAsString(document);
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathEvaluatesTo(String message,
String expectedValue,
String xpathExpression,
SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
String actualValue = expression.evaluateAsString(document);
Assert.assertEquals(message, expectedValue, actualValue);
}
protected void assertXpathExists(String message, String xpathExpression, SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
Node node = expression.evaluateAsNode(document);
Assert.assertNotNull(message, node);
}
protected void assertXpathExists(String message, String xpathExpression, SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
Node node = expression.evaluateAsNode(document);
Assert.assertNotNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
Node node = expression.evaluateAsNode(document);
Assert.assertNull(message, node);
}
protected void assertXpathNotExists(String message, String xpathExpression, SOAPMessage soapMessage) {
XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpathExpression, namespaces);
Document document = soapMessage.getSOAPPart();
Node node = expression.evaluateAsNode(document);
Assert.assertNull(message, node);
}
protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is));
}
finally {
is.close();
}
}
protected SaajSoapMessage loadSaajMessage(String fileName) throws SOAPException, IOException {
MimeHeaders mimeHeaders = new MimeHeaders();
mimeHeaders.addHeader("Content-Type", "text/xml");
Resource resource = new ClassPathResource(fileName, getClass());
InputStream is = resource.getInputStream();
try {
assertTrue("Could not load SAAJ message [" + resource + "]", resource.exists());
is = resource.getInputStream();
return new SaajSoapMessage(messageFactory.createMessage(mimeHeaders, is));
}
finally {
is.close();
}
}
protected void onSetup() throws Exception {
}
protected void onSetup() throws Exception {
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -33,150 +33,150 @@ import static org.junit.Assert.*;
public class XwsSecurityInterceptorTest {
private MessageFactory messageFactory;
private MessageFactory messageFactory;
@Before
public void setUp() throws Exception {
messageFactory = MessageFactory.newInstance();
}
@Before
public void setUp() throws Exception {
messageFactory = MessageFactory.newInstance();
}
@Test
public void testHandleServerRequest() throws Exception {
final SOAPMessage request = messageFactory.createMessage();
final SOAPMessage validatedRequest = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Test
public void testHandleServerRequest() throws Exception {
final SOAPMessage request = messageFactory.createMessage();
final SOAPMessage validatedRequest = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
fail("secure not expected");
}
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
fail("secure not expected");
}
@Override
protected void validateMessage(SoapMessage message, MessageContext messageContext)
throws WsSecurityValidationException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage());
saajSoapMessage.setSaajMessage(validatedRequest);
}
@Override
protected void validateMessage(SoapMessage message, MessageContext messageContext)
throws WsSecurityValidationException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage());
saajSoapMessage.setSaajMessage(validatedRequest);
}
};
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
interceptor.handleRequest(context, null);
assertEquals("Invalid request", validatedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage());
}
};
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
interceptor.handleRequest(context, null);
assertEquals("Invalid request", validatedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage());
}
@Test
public void testHandleServerResponse() throws Exception {
final SOAPMessage securedResponse = messageFactory.createMessage();
final boolean[] cleanupCalled = new boolean[1];
cleanupCalled[0] = false;
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Test
public void testHandleServerResponse() throws Exception {
final SOAPMessage securedResponse = messageFactory.createMessage();
final boolean[] cleanupCalled = new boolean[1];
cleanupCalled[0] = false;
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage message, MessageContext messageContext)
throws XwsSecuritySecurementException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
saajSoapMessage.setSaajMessage(securedResponse);
}
@Override
protected void secureMessage(SoapMessage message, MessageContext messageContext)
throws XwsSecuritySecurementException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) message;
saajSoapMessage.setSaajMessage(securedResponse);
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
@Override
protected void cleanUp() {
cleanupCalled[0] = true;
}
};
@Override
protected void cleanUp() {
cleanupCalled[0] = true;
}
};
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleResponse(context, null);
interceptor.afterCompletion(context, null, null);
assertEquals("Invalid response", securedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage());
assertTrue("Cleanup not called", cleanupCalled[0]);
}
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleResponse(context, null);
interceptor.afterCompletion(context, null, null);
assertEquals("Invalid response", securedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage());
assertTrue("Cleanup not called", cleanupCalled[0]);
}
@Test
public void testHandleServerFault() throws Exception {
final boolean[] cleanupCalled = new boolean[1];
cleanupCalled[0] = false;
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Test
public void testHandleServerFault() throws Exception {
final boolean[] cleanupCalled = new boolean[1];
cleanupCalled[0] = false;
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Override
protected void cleanUp() {
cleanupCalled[0] = true;
}
};
@Override
protected void cleanUp() {
cleanupCalled[0] = true;
}
};
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleFault(context, null);
interceptor.afterCompletion(context, null, null);
assertTrue("Cleanup not called", cleanupCalled[0]);
}
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleFault(context, null);
interceptor.afterCompletion(context, null, null);
assertTrue("Cleanup not called", cleanupCalled[0]);
}
@Test
public void testHandleClientRequest() throws Exception {
final SOAPMessage request = messageFactory.createMessage();
final SOAPMessage securedRequest = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Test
public void testHandleClientRequest() throws Exception {
final SOAPMessage request = messageFactory.createMessage();
final SOAPMessage securedRequest = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage());
saajSoapMessage.setSaajMessage(securedRequest);
}
@Override
protected void secureMessage(SoapMessage soapMessage, MessageContext messageContext)
throws XwsSecuritySecurementException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
assertEquals("Invalid message", request, saajSoapMessage.getSaajMessage());
saajSoapMessage.setSaajMessage(securedRequest);
}
@Override
protected void validateMessage(SoapMessage message, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
@Override
protected void validateMessage(SoapMessage message, MessageContext messageContext)
throws WsSecurityValidationException {
fail("validate not expected");
}
};
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
interceptor.handleRequest(context);
assertEquals("Invalid request", securedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage());
}
};
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
interceptor.handleRequest(context);
assertEquals("Invalid request", securedRequest, ((SaajSoapMessage) context.getRequest()).getSaajMessage());
}
@Test
public void testHandleClientResponse() throws Exception {
final SOAPMessage validatedResponse = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Test
public void testHandleClientResponse() throws Exception {
final SOAPMessage validatedResponse = messageFactory.createMessage();
XwsSecurityInterceptor interceptor = new XwsSecurityInterceptor() {
@Override
protected void secureMessage(SoapMessage message, MessageContext messageContext)
throws XwsSecuritySecurementException {
fail("secure not expected");
}
@Override
protected void secureMessage(SoapMessage message, MessageContext messageContext)
throws XwsSecuritySecurementException {
fail("secure not expected");
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
saajSoapMessage.setSaajMessage(validatedResponse);
}
@Override
protected void validateMessage(SoapMessage soapMessage, MessageContext messageContext)
throws WsSecurityValidationException {
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) soapMessage;
saajSoapMessage.setSaajMessage(validatedResponse);
}
};
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleResponse(context);
assertEquals("Invalid response", validatedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage());
}
};
SOAPMessage request = messageFactory.createMessage();
MessageContext context =
new DefaultMessageContext(new SaajSoapMessage(request), new SaajSoapMessageFactory(messageFactory));
context.getResponse();
interceptor.handleResponse(context);
assertEquals("Invalid response", validatedResponse, ((SaajSoapMessage) context.getResponse()).getSaajMessage());
}
}

View File

@@ -33,112 +33,112 @@ import static org.junit.Assert.*;
public class XwssMessageInterceptorEncryptTest extends AbstractXwssMessageInterceptorKeyStoreTestCase {
@Test
@Ignore("Does not run under JDK 1.8")
public void encryptDefaultCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
@Ignore("Does not run under JDK 1.8")
public void encryptDefaultCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof EncryptionKeyCallback) {
EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
EncryptionKeyCallback.AliasX509CertificateRequest request =
(EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "", request.getAlias());
request.setX509Certificate(certificate);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof EncryptionKeyCallback) {
EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
EncryptionKeyCallback.AliasX509CertificateRequest request =
(EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "", request.getAlias());
request.setX509Certificate(certificate);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result);
}
@Test
@Ignore("Does not run under JDK 1.8")
public void encryptAlias() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-alias-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
@Ignore("Does not run under JDK 1.8")
public void encryptAlias() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("encrypt-alias-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof EncryptionKeyCallback) {
EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
EncryptionKeyCallback.AliasX509CertificateRequest request =
(EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "alias", request.getAlias());
request.setX509Certificate(certificate);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof EncryptionKeyCallback) {
EncryptionKeyCallback keyCallback = (EncryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof EncryptionKeyCallback.AliasX509CertificateRequest) {
EncryptionKeyCallback.AliasX509CertificateRequest request =
(EncryptionKeyCallback.AliasX509CertificateRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "alias", request.getAlias());
request.setX509Certificate(certificate);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/xenc:EncryptedKey", result);
}
@Test
@Ignore("Does not run under JDK 1.8")
public void testDecrypt() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("decrypt-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
@Ignore("Does not run under JDK 1.8")
public void testDecrypt() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("decrypt-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof DecryptionKeyCallback) {
DecryptionKeyCallback keyCallback = (DecryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof DecryptionKeyCallback.X509CertificateBasedRequest) {
DecryptionKeyCallback.X509CertificateBasedRequest request =
(DecryptionKeyCallback.X509CertificateBasedRequest) keyCallback.getRequest();
assertEquals("Invalid certificate", certificate, request.getX509Certificate());
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("encrypted-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof DecryptionKeyCallback) {
DecryptionKeyCallback keyCallback = (DecryptionKeyCallback) callback;
if (keyCallback.getRequest() instanceof DecryptionKeyCallback.X509CertificateBasedRequest) {
DecryptionKeyCallback.X509CertificateBasedRequest request =
(DecryptionKeyCallback.X509CertificateBasedRequest) keyCallback.getRequest();
assertEquals("Invalid certificate", certificate, request.getX509Certificate());
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("encrypted-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
}

View File

@@ -33,107 +33,107 @@ import static org.junit.Assert.*;
public class XwssMessageInterceptorSignTest extends AbstractXwssMessageInterceptorKeyStoreTestCase {
@Test
public void testSignDefaultCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("sign-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
public void testSignDefaultCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("sign-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof SignatureKeyCallback) {
SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback;
if (keyCallback.getRequest() instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) {
SignatureKeyCallback.DefaultPrivKeyCertRequest request =
(SignatureKeyCallback.DefaultPrivKeyCertRequest) keyCallback.getRequest();
request.setX509Certificate(certificate);
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature",
result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof SignatureKeyCallback) {
SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback;
if (keyCallback.getRequest() instanceof SignatureKeyCallback.DefaultPrivKeyCertRequest) {
SignatureKeyCallback.DefaultPrivKeyCertRequest request =
(SignatureKeyCallback.DefaultPrivKeyCertRequest) keyCallback.getRequest();
request.setX509Certificate(certificate);
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature",
result);
}
@Test
public void testSignAlias() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("sign-alias-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
public void testSignAlias() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("sign-alias-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof SignatureKeyCallback) {
SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback;
if (keyCallback.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) {
SignatureKeyCallback.AliasPrivKeyCertRequest request =
(SignatureKeyCallback.AliasPrivKeyCertRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "alias", request.getAlias());
request.setX509Certificate(certificate);
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature",
result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof SignatureKeyCallback) {
SignatureKeyCallback keyCallback = (SignatureKeyCallback) callback;
if (keyCallback.getRequest() instanceof SignatureKeyCallback.AliasPrivKeyCertRequest) {
SignatureKeyCallback.AliasPrivKeyCertRequest request =
(SignatureKeyCallback.AliasPrivKeyCertRequest) keyCallback.getRequest();
assertEquals("Invalid alias", "alias", request.getAlias());
request.setX509Certificate(certificate);
request.setPrivateKey(privateKey);
}
else {
fail("Unexpected request");
}
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathExists("BinarySecurityToken does not exist",
"SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:BinarySecurityToken", result);
assertXpathExists("Signature does not exist", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/ds:Signature",
result);
}
@Test
public void testValidateCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("requireSignature-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
public void testValidateCertificate() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("requireSignature-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof CertificateValidationCallback) {
CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback;
validationCallback.setValidator(new CertificateValidationCallback.CertificateValidator() {
public boolean validate(X509Certificate passedCertificate) {
assertEquals("Invalid certificate", certificate, passedCertificate);
return true;
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("signed-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof CertificateValidationCallback) {
CertificateValidationCallback validationCallback = (CertificateValidationCallback) callback;
validationCallback.setValidator(new CertificateValidationCallback.CertificateValidator() {
public boolean validate(X509Certificate passedCertificate) {
assertEquals("Invalid certificate", certificate, passedCertificate);
return true;
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("signed-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
}

View File

@@ -35,244 +35,244 @@ import static org.junit.Assert.*;
public class XwssMessageInterceptorUsernameTokenTest extends AbstractXwssMessageInterceptorTestCase {
@Test
@Test
public void testAddUsernameTokenDigest() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-digest-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-digest-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()",
result);
assertXpathExists("Password does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']",
result);
assertXpathExists("Nonce does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce",
result);
assertXpathExists("Created does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created",
result);
}
@Test
public void testAddUsernameTokenPlainText() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-plainText-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", result);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
result);
}
@Test
public void testAddUsernameTokenPlainTextNonce() throws Exception {
interceptor.setPolicyConfiguration(
new ClassPathResource("usernameToken-plainText-nonce-config.xml",
getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()",
result);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
result);
assertXpathExists("Nonce does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce",
result);
assertXpathExists("Created does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created",
result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()",
result);
assertXpathExists("Password does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest']",
result);
assertXpathExists("Nonce does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce",
result);
assertXpathExists("Created does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created",
result);
}
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
interceptor
.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
public void testAddUsernameTokenPlainText() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("usernameToken-plainText-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() {
public boolean validate(PasswordValidationCallback.Request request) {
if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
PasswordValidationCallback.PlainTextPasswordRequest passwordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
assertEquals("Invalid password", "Ernie", passwordRequest.getPassword());
return true;
}
else {
fail("Unexpected request");
return false;
}
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()", result);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
result);
}
@Test
public void testValidateUsernameTokenPlainTextNonce() throws Exception {
interceptor
.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-nonce-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
public void testAddUsernameTokenPlainTextNonce() throws Exception {
interceptor.setPolicyConfiguration(
new ClassPathResource("usernameToken-plainText-nonce-config.xml",
getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() {
public boolean validate(PasswordValidationCallback.Request request) {
if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
PasswordValidationCallback.PlainTextPasswordRequest passwordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
assertEquals("Invalid password", "Ernie", passwordRequest.getPassword());
return true;
}
else {
fail("Unexpected request");
return false;
}
}
});
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback;
validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() {
public void validate(TimestampValidationCallback.Request request) {
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-nonce-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof UsernameCallback) {
((UsernameCallback) callback).setUsername("Bert");
}
else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback) callback;
passwordCallback.setPassword("Ernie");
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("empty-soap.xml");
interceptor.secureMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathEvaluatesTo("Invalid Username", "Bert",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Username/text()",
result);
assertXpathEvaluatesTo("Invalid Password", "Ernie",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Password[@Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText']/text()",
result);
assertXpathExists("Nonce does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsse:Nonce",
result);
assertXpathExists("Created does not exist",
"/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security/wsse:UsernameToken/wsu:Created",
result);
}
@Test
public void testValidateUsernameTokenDigest() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-digest-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Test
public void testValidateUsernameTokenPlainText() throws Exception {
interceptor
.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest passwordRequest =
(PasswordValidationCallback.DigestPasswordRequest) validationCallback.getRequest();
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
passwordRequest.setPassword("Ernie");
validationCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
else {
fail("Unexpected request");
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback;
validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() {
public void validate(TimestampValidationCallback.Request request) {
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenDigest-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() {
public boolean validate(PasswordValidationCallback.Request request) {
if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
PasswordValidationCallback.PlainTextPasswordRequest passwordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
assertEquals("Invalid password", "Ernie", passwordRequest.getPassword());
return true;
}
else {
fail("Unexpected request");
return false;
}
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Test
public void testValidateUsernameTokenPlainTextNonce() throws Exception {
interceptor
.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-plainText-nonce-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
validationCallback.setValidator(new PasswordValidationCallback.PasswordValidator() {
public boolean validate(PasswordValidationCallback.Request request) {
if (request instanceof PasswordValidationCallback.PlainTextPasswordRequest) {
PasswordValidationCallback.PlainTextPasswordRequest passwordRequest =
(PasswordValidationCallback.PlainTextPasswordRequest) request;
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
assertEquals("Invalid password", "Ernie", passwordRequest.getPassword());
return true;
}
else {
fail("Unexpected request");
return false;
}
}
});
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback;
validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() {
public void validate(TimestampValidationCallback.Request request) {
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenPlainText-nonce-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
@Test
public void testValidateUsernameTokenDigest() throws Exception {
interceptor.setPolicyConfiguration(new ClassPathResource("requireUsernameToken-digest-config.xml", getClass()));
CallbackHandler handler = new AbstractCallbackHandler() {
@Override
protected void handleInternal(Callback callback) {
if (callback instanceof PasswordValidationCallback) {
PasswordValidationCallback validationCallback = (PasswordValidationCallback) callback;
if (validationCallback.getRequest() instanceof PasswordValidationCallback.DigestPasswordRequest) {
PasswordValidationCallback.DigestPasswordRequest passwordRequest =
(PasswordValidationCallback.DigestPasswordRequest) validationCallback.getRequest();
assertEquals("Invalid username", "Bert", passwordRequest.getUsername());
passwordRequest.setPassword("Ernie");
validationCallback.setValidator(new PasswordValidationCallback.DigestPasswordValidator());
}
else {
fail("Unexpected request");
}
}
else if (callback instanceof TimestampValidationCallback) {
TimestampValidationCallback validationCallback = (TimestampValidationCallback) callback;
validationCallback.setValidator(new TimestampValidationCallback.TimestampValidator() {
public void validate(TimestampValidationCallback.Request request) {
}
});
}
else {
fail("Unexpected callback");
}
}
};
interceptor.setCallbackHandler(handler);
interceptor.afterPropertiesSet();
SaajSoapMessage message = loadSaajMessage("usernameTokenDigest-soap.xml");
interceptor.validateMessage(message, null);
SOAPMessage result = message.getSaajMessage();
assertNotNull("No result returned", result);
assertXpathNotExists("Security Header not removed", "/SOAP-ENV:Envelope/SOAP-ENV:Header/wsse:Security", result);
}
}

View File

@@ -22,24 +22,24 @@ import org.junit.Test;
public class DefaultTimestampValidatorTest {
private DefaultTimestampValidator validator;
private DefaultTimestampValidator validator;
@Before
public void setUp() throws Exception {
validator = new DefaultTimestampValidator();
}
@Before
public void setUp() throws Exception {
validator = new DefaultTimestampValidator();
}
@Test
public void testValidate() throws Exception {
TimestampValidationCallback.Request request = new TimestampValidationCallback.UTCTimestampRequest(
"2006-09-25T20:42:50Z", "2107-09-25T20:42:50Z", 100, Long.MAX_VALUE);
validator.validate(request);
}
@Test
public void testValidate() throws Exception {
TimestampValidationCallback.Request request = new TimestampValidationCallback.UTCTimestampRequest(
"2006-09-25T20:42:50Z", "2107-09-25T20:42:50Z", 100, Long.MAX_VALUE);
validator.validate(request);
}
@Test
public void testValidateNoExpired() throws Exception {
TimestampValidationCallback.Request request =
new TimestampValidationCallback.UTCTimestampRequest("2006-09-25T20:42:50Z", null, 100, Long.MAX_VALUE);
validator.validate(request);
}
@Test
public void testValidateNoExpired() throws Exception {
TimestampValidationCallback.Request request =
new TimestampValidationCallback.UTCTimestampRequest("2006-09-25T20:42:50Z", null, 100, Long.MAX_VALUE);
validator.validate(request);
}
}

View File

@@ -21,17 +21,17 @@ import org.junit.Test;
public class KeyStoreCallbackHandlerTest {
private KeyStoreCallbackHandler handler;
private KeyStoreCallbackHandler handler;
@Before
public void setUp() throws Exception {
handler = new KeyStoreCallbackHandler();
}
@Before
public void setUp() throws Exception {
handler = new KeyStoreCallbackHandler();
}
@Test
public void testLoadDefaultTrustStore() throws Exception {
System.setProperty("javax.net.ssl.trustStore",
"/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/");
handler.loadDefaultTrustStore();
}
@Test
public void testLoadDefaultTrustStore() throws Exception {
System.setProperty("javax.net.ssl.trustStore",
"/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/");
handler.loadDefaultTrustStore();
}
}

View File

@@ -25,73 +25,73 @@ import org.junit.Test;
public class SimplePasswordValidationCallbackHandlerTest {
private SimplePasswordValidationCallbackHandler handler;
private SimplePasswordValidationCallbackHandler handler;
@Before
public void setUp() throws Exception {
handler = new SimplePasswordValidationCallbackHandler();
Properties users = new Properties();
users.setProperty("Bert", "Ernie");
handler.setUsers(users);
}
@Before
public void setUp() throws Exception {
handler = new SimplePasswordValidationCallbackHandler();
Properties users = new Properties();
users.setProperty("Bert", "Ernie");
handler.setUsers(users);
}
@Test
public void testPlainTextPasswordValid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
@Test
public void testPlainTextPasswordValid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
@Test
public void testPlainTextPasswordInvalid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
@Test
public void testPlainTextPasswordInvalid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
@Test
public void testPlainTextPasswordNoSuchUser() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Big bird", "Bert");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
@Test
public void testPlainTextPasswordNoSuchUser() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Big bird", "Bert");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
@Test
public void testDigestPasswordValid() throws Exception {
String username = "Bert";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk=";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Authenticated", authenticated);
@Test
public void testDigestPasswordValid() throws Exception {
String username = "Bert";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk=";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Authenticated", authenticated);
}
}
@Test
public void testDigestPasswordInvalid() throws Exception {
String username = "Bert";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
@Test
public void testDigestPasswordInvalid() throws Exception {
String username = "Bert";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
PasswordValidationCallback callback = new PasswordValidationCallback(request);
handler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
}
}

View File

@@ -24,26 +24,26 @@ import org.junit.Test;
public class SimpleUsernamePasswordCallbackHandlerTest {
private SimpleUsernamePasswordCallbackHandler handler;
private SimpleUsernamePasswordCallbackHandler handler;
@Before
public void setUp() throws Exception {
handler = new SimpleUsernamePasswordCallbackHandler();
handler.setUsername("Bert");
handler.setPassword("Ernie");
}
@Before
public void setUp() throws Exception {
handler = new SimpleUsernamePasswordCallbackHandler();
handler.setUsername("Bert");
handler.setPassword("Ernie");
}
@Test
public void testUsernameCallback() throws Exception {
UsernameCallback usernameCallback = new UsernameCallback();
handler.handleInternal(usernameCallback);
Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername());
}
@Test
public void testUsernameCallback() throws Exception {
UsernameCallback usernameCallback = new UsernameCallback();
handler.handleInternal(usernameCallback);
Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername());
}
@Test
public void testPasswordCallback() throws Exception {
PasswordCallback passwordCallback = new PasswordCallback();
handler.handleInternal(passwordCallback);
Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword());
}
@Test
public void testPasswordCallback() throws Exception {
PasswordCallback passwordCallback = new PasswordCallback();
handler.handleInternal(passwordCallback);
Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword());
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -40,78 +40,78 @@ import static org.easymock.EasyMock.*;
public class SpringCertificateValidationCallbackHandlerTest {
private SpringCertificateValidationCallbackHandler callbackHandler;
private SpringCertificateValidationCallbackHandler callbackHandler;
private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
private X509Certificate certificate;
private X509Certificate certificate;
private CertificateValidationCallback callback;
private CertificateValidationCallback callback;
@Before
public void setUp() throws Exception {
callbackHandler = new SpringCertificateValidationCallbackHandler();
authenticationManager = createMock(AuthenticationManager.class);
callbackHandler.setAuthenticationManager(authenticationManager);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream();
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
certificate = (X509Certificate) keyStore.getCertificate("alias");
callback = new CertificateValidationCallback(certificate);
}
@Before
public void setUp() throws Exception {
callbackHandler = new SpringCertificateValidationCallbackHandler();
authenticationManager = createMock(AuthenticationManager.class);
callbackHandler.setAuthenticationManager(authenticationManager);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream();
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
certificate = (X509Certificate) keyStore.getCertificate("alias");
callback = new CertificateValidationCallback(certificate);
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testValidateCertificateValid() throws Exception {
expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class)))
.andReturn(new TestingAuthenticationToken(certificate, null, Collections.<GrantedAuthority>emptyList()));
@Test
public void testValidateCertificateValid() throws Exception {
expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class)))
.andReturn(new TestingAuthenticationToken(certificate, null, Collections.<GrantedAuthority>emptyList()));
replay(authenticationManager);
replay(authenticationManager);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(authenticationManager);
}
verify(authenticationManager);
}
@Test
public void testValidateCertificateInvalid() throws Exception {
expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class)))
.andThrow(new BadCredentialsException(""));
@Test
public void testValidateCertificateInvalid() throws Exception {
expect(authenticationManager.authenticate(isA(X509AuthenticationToken.class)))
.andThrow(new BadCredentialsException(""));
replay(authenticationManager);
replay(authenticationManager);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(authenticationManager);
}
verify(authenticationManager);
}
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -37,105 +37,105 @@ import static org.easymock.EasyMock.*;
public class SpringDigestPasswordValidationCallbackHandlerTest {
private SpringDigestPasswordValidationCallbackHandler callbackHandler;
private SpringDigestPasswordValidationCallbackHandler callbackHandler;
private UserDetailsService userDetailsService;
private UserDetailsService userDetailsService;
private String username;
private String username;
private String password;
private String password;
private PasswordValidationCallback callback;
private PasswordValidationCallback callback;
@Before
public void setUp() throws Exception {
callbackHandler = new SpringDigestPasswordValidationCallbackHandler();
userDetailsService = createMock(UserDetailsService.class);
callbackHandler.setUserDetailsService(userDetailsService);
username = "Bert";
password = "Ernie";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk=";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
callback = new PasswordValidationCallback(request);
}
@Before
public void setUp() throws Exception {
callbackHandler = new SpringDigestPasswordValidationCallbackHandler();
userDetailsService = createMock(UserDetailsService.class);
callbackHandler.setUserDetailsService(userDetailsService);
username = "Bert";
password = "Ernie";
String nonce = "9mdsYDCrjjYRur0rxzYt2oD7";
String passwordDigest = "kwNstEaiFOrI7B31j7GuETYvdgk=";
String creationTime = "2006-06-01T23:48:42Z";
PasswordValidationCallback.DigestPasswordRequest request =
new PasswordValidationCallback.DigestPasswordRequest(username, passwordDigest, nonce, creationTime);
callback = new PasswordValidationCallback(request);
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testAuthenticateUserDigestUserNotFound() throws Exception {
expect(userDetailsService.loadUserByUsername(username)).andThrow(new UsernameNotFoundException(username));
@Test
public void testAuthenticateUserDigestUserNotFound() throws Exception {
expect(userDetailsService.loadUserByUsername(username)).andThrow(new UsernameNotFoundException(username));
replay(userDetailsService);
replay(userDetailsService);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(userDetailsService);
}
verify(userDetailsService);
}
@Test
public void testAuthenticateUserDigestValid() throws Exception {
User user = new User(username, password, true, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
@Test
public void testAuthenticateUserDigestValid() throws Exception {
User user = new User(username, password, true, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
replay(userDetailsService);
replay(userDetailsService);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(userDetailsService);
}
verify(userDetailsService);
}
@Test
public void testAuthenticateUserDigestValidInvalid() throws Exception {
User user = new User(username, "Big bird", true, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
@Test
public void testAuthenticateUserDigestValidInvalid() throws Exception {
User user = new User(username, "Big bird", true, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
replay(userDetailsService);
replay(userDetailsService);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(userDetailsService);
}
verify(userDetailsService);
}
@Test
public void testAuthenticateUserDigestDisabled() throws Exception {
User user = new User(username, "Ernie", false, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
@Test
public void testAuthenticateUserDigestDisabled() throws Exception {
User user = new User(username, "Ernie", false, true, true, true, Collections.<GrantedAuthority>emptyList());
expect(userDetailsService.loadUserByUsername(username)).andReturn(user);
replay(userDetailsService);
replay(userDetailsService);
try {
callbackHandler.handleInternal(callback);
Assert.fail("disabled user authenticated");
} catch (DisabledException expected) {
// expected
}
verify(userDetailsService);
}
try {
callbackHandler.handleInternal(callback);
Assert.fail("disabled user authenticated");
} catch (DisabledException expected) {
// expected
}
verify(userDetailsService);
}
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
}

View File

@@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
@@ -37,72 +37,72 @@ import static org.easymock.EasyMock.*;
public class SpringPlainTextPasswordValidationCallbackHandlerTest {
private SpringPlainTextPasswordValidationCallbackHandler callbackHandler;
private SpringPlainTextPasswordValidationCallbackHandler callbackHandler;
private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
private PasswordValidationCallback callback;
private PasswordValidationCallback callback;
private String username;
private String username;
private String password;
private String password;
@Before
public void setUp() throws Exception {
callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler();
authenticationManager = createMock(AuthenticationManager.class);
callbackHandler.setAuthenticationManager(authenticationManager);
username = "Bert";
password = "Ernie";
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest(username, password);
callback = new PasswordValidationCallback(request);
}
@Before
public void setUp() throws Exception {
callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler();
authenticationManager = createMock(AuthenticationManager.class);
callbackHandler.setAuthenticationManager(authenticationManager);
username = "Bert";
password = "Ernie";
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest(username, password);
callback = new PasswordValidationCallback(request);
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testAuthenticateUserPlainTextValid() throws Exception {
Authentication authResult = new TestingAuthenticationToken(username, password, Collections
.<GrantedAuthority>emptyList());
expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andReturn(authResult);
@Test
public void testAuthenticateUserPlainTextValid() throws Exception {
Authentication authResult = new TestingAuthenticationToken(username, password, Collections
.<GrantedAuthority>emptyList());
expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andReturn(authResult);
replay(authenticationManager);
replay(authenticationManager);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
Assert.assertNotNull("No Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(authenticationManager);
}
verify(authenticationManager);
}
@Test
public void testAuthenticateUserPlainTextInvalid() throws Exception {
expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andThrow(new BadCredentialsException(""));
@Test
public void testAuthenticateUserPlainTextInvalid() throws Exception {
expect(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))).andThrow(new BadCredentialsException(""));
replay(authenticationManager);
replay(authenticationManager);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
verify(authenticationManager);
}
verify(authenticationManager);
}
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
@Test
public void testCleanUp() throws Exception {
TestingAuthenticationToken authentication =
new TestingAuthenticationToken(new Object(), new Object(), Collections.<GrantedAuthority>emptyList());
SecurityContextHolder.getContext().setAuthentication(authentication);
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
CleanupCallback cleanupCallback = new CleanupCallback();
callbackHandler.handleInternal(cleanupCallback);
Assert.assertNull("Authentication created", SecurityContextHolder.getContext().getAuthentication());
}
}

View File

@@ -29,31 +29,31 @@ import org.junit.Test;
public class SpringUsernamePasswordCallbackHandlerTest {
private SpringUsernamePasswordCallbackHandler handler;
private SpringUsernamePasswordCallbackHandler handler;
@Before
public void setUp() throws Exception {
handler = new SpringUsernamePasswordCallbackHandler();
Authentication authentication = new UsernamePasswordAuthenticationToken("Bert", "Ernie");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@Before
public void setUp() throws Exception {
handler = new SpringUsernamePasswordCallbackHandler();
Authentication authentication = new UsernamePasswordAuthenticationToken("Bert", "Ernie");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@After
public void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
@Test
public void testUsernameCallback() throws Exception {
UsernameCallback usernameCallback = new UsernameCallback();
handler.handleInternal(usernameCallback);
Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername());
}
@Test
public void testUsernameCallback() throws Exception {
UsernameCallback usernameCallback = new UsernameCallback();
handler.handleInternal(usernameCallback);
Assert.assertEquals("Invalid username", "Bert", usernameCallback.getUsername());
}
@Test
public void testPasswordCallback() throws Exception {
PasswordCallback passwordCallback = new PasswordCallback();
handler.handleInternal(passwordCallback);
Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword());
}
@Test
public void testPasswordCallback() throws Exception {
PasswordCallback passwordCallback = new PasswordCallback();
handler.handleInternal(passwordCallback);
Assert.assertEquals("Invalid username", "Ernie", passwordCallback.getPassword());
}
}

View File

@@ -26,59 +26,59 @@ import javax.security.auth.x500.X500Principal;
public class CertificateLoginModule implements LoginModule {
private Subject subject;
private Subject subject;
private boolean loginSuccessful = false;
private boolean loginSuccessful = false;
@Override
public boolean abort() {
return true;
}
@Override
public boolean abort() {
return true;
}
@Override
public boolean commit() {
if (!loginSuccessful) {
subject.getPrincipals().clear();
subject.getPrivateCredentials().clear();
return false;
}
return true;
}
@Override
public boolean commit() {
if (!loginSuccessful) {
subject.getPrincipals().clear();
subject.getPrivateCredentials().clear();
return false;
}
return true;
}
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
java.util.Map sharedState,
java.util.Map options) {
this.subject = subject;
}
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
java.util.Map sharedState,
java.util.Map options) {
this.subject = subject;
}
@Override
public boolean login() throws LoginException {
if (subject == null) {
return false;
}
@Override
public boolean login() throws LoginException {
if (subject == null) {
return false;
}
String name = getName(subject);
String name = getName(subject);
loginSuccessful = "CN=Arjen Poutsma,OU=Spring-WS,O=Interface21,L=Amsterdam,ST=Unknown,C=NL".equals(name);
return loginSuccessful;
}
loginSuccessful = "CN=Arjen Poutsma,OU=Spring-WS,O=Interface21,L=Amsterdam,ST=Unknown,C=NL".equals(name);
return loginSuccessful;
}
@Override
public boolean logout() {
subject.getPrincipals().clear();
subject.getPrivateCredentials().clear();
return true;
}
@Override
public boolean logout() {
subject.getPrincipals().clear();
subject.getPrivateCredentials().clear();
return true;
}
private String getName(Subject subject) {
for (Iterator iterator = subject.getPrincipals().iterator(); iterator.hasNext();) {
Principal principal = (Principal) iterator.next();
if (principal instanceof X500Principal) {
return principal.getName();
}
}
return null;
}
private String getName(Subject subject) {
for (Iterator iterator = subject.getPrincipals().iterator(); iterator.hasNext();) {
Principal principal = (Principal) iterator.next();
if (principal instanceof X500Principal) {
return principal.getName();
}
}
return null;
}
}

View File

@@ -29,35 +29,35 @@ import org.junit.Test;
public class JaasCertificateValidationCallbackHandlerTest {
private JaasCertificateValidationCallbackHandler callbackHandler;
private JaasCertificateValidationCallbackHandler callbackHandler;
private CertificateValidationCallback callback;
private CertificateValidationCallback callback;
@Before
public void setUp() throws Exception {
System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString());
callbackHandler = new JaasCertificateValidationCallbackHandler();
callbackHandler.setLoginContextName("Certificate");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream();
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
X509Certificate certificate = (X509Certificate) keyStore.getCertificate("alias");
callback = new CertificateValidationCallback(certificate);
}
@Before
public void setUp() throws Exception {
System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString());
callbackHandler = new JaasCertificateValidationCallbackHandler();
callbackHandler.setLoginContextName("Certificate");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = null;
try {
is = new ClassPathResource("/org/springframework/ws/soap/security/xwss/test-keystore.jks").getInputStream();
keyStore.load(is, "password".toCharArray());
}
finally {
if (is != null) {
is.close();
}
}
X509Certificate certificate = (X509Certificate) keyStore.getCertificate("alias");
callback = new CertificateValidationCallback(certificate);
}
@Test
public void testValidateCertificateValid() throws Exception {
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
@Test
public void testValidateCertificateValid() throws Exception {
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
}

View File

@@ -23,33 +23,33 @@ import org.junit.Test;
public class JaasPlainTextPasswordValidationCallbackHandlerTest {
private JaasPlainTextPasswordValidationCallbackHandler callbackHandler;
private JaasPlainTextPasswordValidationCallbackHandler callbackHandler;
@Before
public void setUp() throws Exception {
System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString());
callbackHandler = new JaasPlainTextPasswordValidationCallbackHandler();
callbackHandler.setLoginContextName("PlainText");
}
@Before
public void setUp() throws Exception {
System.setProperty("java.security.auth.login.config", getClass().getResource("jaas.config").toString());
callbackHandler = new JaasPlainTextPasswordValidationCallbackHandler();
callbackHandler.setLoginContextName("PlainText");
}
@Test
public void testAuthenticateUserPlainTextValid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
@Test
public void testAuthenticateUserPlainTextValid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Ernie");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertTrue("Not authenticated", authenticated);
}
@Test
public void testAuthenticateUserPlainTextInvalid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
@Test
public void testAuthenticateUserPlainTextInvalid() throws Exception {
PasswordValidationCallback.PlainTextPasswordRequest request =
new PasswordValidationCallback.PlainTextPasswordRequest("Bert", "Big bird");
PasswordValidationCallback callback = new PasswordValidationCallback(request);
callbackHandler.handleInternal(callback);
boolean authenticated = callback.getResult();
Assert.assertFalse("Authenticated", authenticated);
}
}

View File

@@ -30,110 +30,110 @@ import javax.security.auth.spi.LoginModule;
public class PlainTextLoginModule implements LoginModule {
private Subject subject;
private Subject subject;
private CallbackHandler callbackHandler;
private CallbackHandler callbackHandler;
private boolean success;
private boolean success;
private List<Principal> principals = new ArrayList<Principal>();
private List<Principal> principals = new ArrayList<Principal>();
@Override
public boolean abort() {
success = false;
logout();
return true;
}
@Override
public boolean abort() {
success = false;
logout();
return true;
}
@Override
public boolean commit() throws LoginException {
if (success) {
if (subject.isReadOnly()) {
throw new LoginException("Subject is read-only");
}
try {
subject.getPrincipals().addAll(principals);
principals.clear();
return true;
}
catch (Exception e) {
throw new LoginException(e.getMessage());
}
}
else {
principals.clear();
}
return true;
}
@Override
public boolean commit() throws LoginException {
if (success) {
if (subject.isReadOnly()) {
throw new LoginException("Subject is read-only");
}
try {
subject.getPrincipals().addAll(principals);
principals.clear();
return true;
}
catch (Exception e) {
throw new LoginException(e.getMessage());
}
}
else {
principals.clear();
}
return true;
}
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
java.util.Map sharedState,
java.util.Map options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
}
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
java.util.Map sharedState,
java.util.Map options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
}
@Override
public boolean login() throws LoginException {
if (callbackHandler == null) {
return false;
}
try {
NameCallback nameCallback = new NameCallback("Username: ");
PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
Callback[] callbacks = new Callback[]{nameCallback, passwordCallback};
@Override
public boolean login() throws LoginException {
if (callbackHandler == null) {
return false;
}
try {
NameCallback nameCallback = new NameCallback("Username: ");
PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
Callback[] callbacks = new Callback[]{nameCallback, passwordCallback};
callbackHandler.handle(callbacks);
callbackHandler.handle(callbacks);
String username = nameCallback.getName();
String password = new String(passwordCallback.getPassword());
String username = nameCallback.getName();
String password = new String(passwordCallback.getPassword());
((PasswordCallback) callbacks[1]).clearPassword();
((PasswordCallback) callbacks[1]).clearPassword();
success = validate(username, password);
success = validate(username, password);
callbacks[0] = null;
callbacks[1] = null;
callbacks[0] = null;
callbacks[1] = null;
if (!success) {
throw new LoginException("Authentication failed: Password does not match");
}
if (!success) {
throw new LoginException("Authentication failed: Password does not match");
}
return true;
}
catch (LoginException ex) {
throw ex;
}
catch (Exception ex) {
success = false;
throw new LoginException(ex.getMessage());
}
}
return true;
}
catch (LoginException ex) {
throw ex;
}
catch (Exception ex) {
success = false;
throw new LoginException(ex.getMessage());
}
}
private boolean validate(String username, String password) {
if ("Bert".equals(username) && "Ernie".equals(password)) {
this.principals.add(new SimplePrincipal(username));
return true;
}
else {
return false;
}
}
private boolean validate(String username, String password) {
if ("Bert".equals(username) && "Ernie".equals(password)) {
this.principals.add(new SimplePrincipal(username));
return true;
}
else {
return false;
}
}
@Override
public boolean logout() {
principals.clear();
@Override
public boolean logout() {
principals.clear();
Iterator iterator = subject.getPrincipals(SimplePrincipal.class).iterator();
while (iterator.hasNext()) {
SimplePrincipal principal = (SimplePrincipal) iterator.next();
subject.getPrincipals().remove(principal);
}
Iterator iterator = subject.getPrincipals(SimplePrincipal.class).iterator();
while (iterator.hasNext()) {
SimplePrincipal principal = (SimplePrincipal) iterator.next();
subject.getPrincipals().remove(principal);
}
return true;
}
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More