CXF WS, Interceptor: stop processing, respond with fault

Alex picture Alex · Nov 29, 2011 · Viewed 9.7k times · Source

I'm scratching my head over this: Using an Interceptor to check a few SOAP headers, how can I abort the interceptor chain but still respond with an error to the user?

Throwing a Fault works regarding the output, but the request is still being processed and I'd rather not have all services check for some flag in the message context.

Aborting with "message.getInterceptorChain().abort();" really aborts all processing, but then there's also nothing returned to the client.

What's the right way to go?

public class HeadersInterceptor extends AbstractSoapInterceptor {

    public HeadersInterceptor() {
        super(Phase.PRE_LOGICAL);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        Exchange exchange = message.getExchange();
        BindingOperationInfo bop = exchange.getBindingOperationInfo();
        Method action = ((MethodDispatcher) exchange.get(Service.class)
                .get(MethodDispatcher.class.getName())).getMethod(bop);

        if (action.isAnnotationPresent(NeedsHeaders.class)
                && !headersPresent(message)) {
            Fault fault = new Fault(new Exception("No headers Exception"));
            fault.setFaultCode(new QName("Client"));

            try {
                Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().newDocument();
                Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "mynamespace");
                detail.setTextContent("Missing some headers...blah");
                fault.setDetail(detail);

            } catch (ParserConfigurationException e) {
            }

            // bad: message.getInterceptorChain().abort();
            throw fault;
        }
    }
}

Answer

Alex picture Alex · Dec 11, 2011

Following the suggestion by Donal Fellows I'm adding an answer to my question.

CXF heavily relies on Spring's AOP which can cause problems of all sorts, at least here it did. I'm providing the complete code for you. Using open source projects I think it's just fair to provide my own few lines of code for anyone who might decide not to use WS-Security (I'm expecting my services to run on SSL only). I wrote most of it by browsing the CXF sources.

Please, comment if you think there's a better approach.

/**
 * Checks the requested action for AuthenticationRequired annotation and tries
 * to login using SOAP headers username/password.
 * 
 * @author Alexander Hofbauer
 */
public class AuthInterceptor extends AbstractSoapInterceptor {
    public static final String KEY_USER = "UserAuth";

    @Resource
    UserService userService;

    public AuthInterceptor() {
        // process after unmarshalling, so that method and header info are there
        super(Phase.PRE_LOGICAL);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        Logger.getLogger(AuthInterceptor.class).trace("Intercepting service call");

        Exchange exchange = message.getExchange();
        BindingOperationInfo bop = exchange.getBindingOperationInfo();
        Method action = ((MethodDispatcher) exchange.get(Service.class)
                .get(MethodDispatcher.class.getName())).getMethod(bop);

        if (action.isAnnotationPresent(AuthenticationRequired.class)
                && !authenticate(message)) {
            Fault fault = new Fault(new Exception("Authentication failed"));
            fault.setFaultCode(new QName("Client"));

            try {
                Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().newDocument();
                Element detail = doc.createElementNS(Soap12.SOAP_NAMESPACE, "test");
                detail.setTextContent("Failed to authenticate.\n" +
                        "Please make sure to send correct SOAP headers username and password");
                fault.setDetail(detail);

            } catch (ParserConfigurationException e) {
            }

            throw fault;
        }
    }

    private boolean authenticate(SoapMessage msg) {
        Element usernameNode = null;
        Element passwordNode = null;

        for (Header header : msg.getHeaders()) {
            if (header.getName().getLocalPart().equals("username")) {
                usernameNode = (Element) header.getObject();
            } else if (header.getName().getLocalPart().equals("password")) {
                passwordNode = (Element) header.getObject();
            }
        }

        if (usernameNode == null || passwordNode == null) {
            return false;
        }
        String username = usernameNode.getChildNodes().item(0).getNodeValue();
        String password = passwordNode.getChildNodes().item(0).getNodeValue();

        User user = null;
        try {
            user = userService.loginUser(username, password);
        } catch (BusinessException e) {
            return false;
        }
        if (user == null) {
            return false;
        }

        msg.put(KEY_USER, user);
        return true;
    }
}

As mentioned above, here's the ExceptionHandler/-Logger. At first I wasn't able to use it in combination with JAX-RS (also via CXF, JAX-WS works fine now). I don't need JAX-RS anyway, so that problem is gone now.

@Aspect
public class ExceptionHandler {
    @Resource
    private Map<String, Boolean> registeredExceptions;


    /**
     * Everything in my project.
     */
    @Pointcut("within(org.myproject..*)")
    void inScope() {
    }

    /**
     * Every single method.
     */
    @Pointcut("execution(* *(..))")
    void anyOperation() {
    }

    /**
     * Log every Throwable.
     * 
     * @param t
     */
    @AfterThrowing(pointcut = "inScope() && anyOperation()", throwing = "t")
    public void afterThrowing(Throwable t) {
        StackTraceElement[] trace = t.getStackTrace();
        Logger logger = Logger.getLogger(ExceptionHandler.class);

        String info;
        if (trace.length > 0) {
            info = trace[0].getClassName() + ":" + trace[0].getLineNumber()
                    + " threw " + t.getClass().getName();
        } else {
            info = "Caught throwable with empty stack trace";
        }
        logger.warn(info + "\n" + t.getMessage());
        logger.debug("Stacktrace", t);
    }

    /**
     * Handles all exceptions according to config file.
     * Unknown exceptions are always thrown, registered exceptions only if they
     * are set to true in config file.
     * 
     * @param pjp
     * @throws Throwable
     */
    @Around("inScope() && anyOperation()")
    public Object handleThrowing(ProceedingJoinPoint pjp) throws Throwable {
        try {
            Object ret = pjp.proceed();
            return ret;
        } catch (Throwable t) {
            // We don't care about unchecked Exceptions
            if (!(t instanceof Exception)) {
                return null;
            }

            Boolean throwIt = registeredExceptions.get(t.getClass().getName());
            if (throwIt == null || throwIt) {
                throw t;
            }
        }
        return null;
    }
}