CXF WS, Interceptor: stop processing, respond with fault
Asked Answered
O

3

7

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;
        }
    }
}
Octoroon answered 29/11, 2011 at 19:12 Comment(6)
You can't just throw a fault and let CXF handle the rest?Spooky
Yes, I can throw that Fault and the client then receives a fault response which is absolutely what I want, but the request is still processed in the WebServices. This forces me to check whether the client is authenticated in every method in every WebService which is exactly what I don't want to do (cross-cutting and violating DRY).Octoroon
I asked because when I checked the source of the code that implements the processing chain, it seems to handle faults by doing the abort internally. The code's not 100% clear though.Spooky
I found out that for some reason CXF did not like my exception handling with AOP. After debugging for hours and rewriting it problems seem to be gone and behaviour is as expected: throwing a Fault stop processing.Octoroon
In that case, you should write up your fix as an answer; self-answering is encouraged here.Spooky
@DonalFellows OK, I'm going to do that. I'm quite new here obviously ;)Octoroon
O
3

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;
    }
}
Octoroon answered 11/12, 2011 at 12:18 Comment(0)
S
1

Short answer, the right way to abort in a client-side interceptor before the sending the request is to create the Fault with a wrapped exception :

throw new Fault(
      new ClientException( // or any non-Fault exception, else blocks in
      // abstractClient.checkClientException() (waits for missing response code)
      "Error before sending the request"), Fault.FAULT_CODE_CLIENT);

Thanks to post contributors for helping figuring it out.

Seagraves answered 16/10, 2013 at 16:23 Comment(0)
C
1

CXF allows you to specify that your interceptor goes before or after certain interceptors. If your interceptor is processing on the inbound side (which based on your description is the case) there is an interceptor called CheckFaultInterceptor. You can configure your interceptor to go before it:

public HeadersInterceptor(){
    super(Phase.PRE_LOGICAL);
    getBefore().add(CheckFaultInterceptor.class.getName());
}

The check fault interceptor in theory checks if a fault has occurred. If one has, it aborts the interceptor chain and invokes the fault handler chain.

I have not yet been able to test this (it is fully based on the available documentation I've come across trying to solve a related problem)

Concelebrate answered 6/2, 2014 at 16:1 Comment(1)
Also, just as an additional point, putting an interceptor that throws a fault in a phase before the one you use is a bad idea - it doesn't populate necessary fields in the fault, causing exceptions in the CXF fault handling. I've had trouble in versions of CXF past 2.4.3 with the exception not being handled properly in regards to closing piped streams, which caused the application to hang indefinitely (specifically encountered with with 2.7.6 and 2.7.7, where it threw the NPE but still returned properly in 2.4.3).Concelebrate

© 2022 - 2024 — McMap. All rights reserved.