jax-rs with cxf interceptors and callback handler

2019-09-13 01:54发布

问题:

I want to transform an existing XML-based webservice to a REST webservice. While the services are working already, I'm struggling with implementing the security.

In the former implementation, we used interceptors like this (file ws-server-context.xml):

<jaxws:endpoint id="someService" implementor="..." address="/..." >
    <jaxws:inInterceptors>
        <bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />
        <bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
            <constructor-arg>
                <map>
                    <entry key="action" value="UsernameToken" />
                    <entry key="passwordType" value="PasswordText" />
                    <entry key="passwordCallbackRef" value-ref="sessionService" />
                </map>
            </constructor-arg>
        </bean>
    </jaxws:inInterceptors>
</jaxws:endpoint>

Whenever the address of this endpoint is called, the method handle(Callback[] callbacks) of the bean sessionService is invoked, which checks for proper credentials (username + token). This bean implements the interface CallbackHandler.

How can this approach be implemented in JAX-RS? The endpoints are defined at the webservice classes themself (@Path), so do I need to use any annotations there? How do I register the interceptors?

Thanks for your help!

回答1:

Instead of the interceptor, you can declare a filter in your web.xml -

<filter>
        <display-name>MyFilter</display-name>
        <filter-name>MyFilter</filter-name>
        <filter-class>com.*.MyFilter</filter-class>
 </filter>
 <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern></url-pattern> <!-- keep this same as your rest servlet's url pattern -->
 </filter-mapping>

This class will be called before your JAX-RS implementation.

You can refer to the callBackHandler from within the filter class.