I had blogged about how to setup XFire with WS-Security a while ago and since then the XFire 1.x series as we know it is dead, instead Apache’s CXF can be considered XFire 2.0. CXF improves over XFire in many areas including better architecture and more importantly easier message handling and manipulation. In this entry, we’ll setup a CXF application that secures its services using CXF’s WS-Security features.
Before I get to the example I want to mention some of the major changes that I noticed in CXF:
- Interceptors instead of handlers: Handlers are out and are replaced with a much more common concept of interceptors (if you’re from the Struts2/Webwork world you know what they are). Interceptors are created by extending the AbstractPhaseInterceptor class which forces you to implement handleMessage(Message). Note that you must specify the phase where you want each interceptor executed.
- Access to MessageContext: In XFire, the MessageContext was always available in your handlers. In CXF you don’t have access to it in the interceptor but you can get contextual properties using the message.getContextualProperty(String) methods. Access to the MessageContext is also available using the @Resource annotation as described here but this only works in service implementations.
- JAXWS Endpoints: Spring service classes must be exposed using the <jaxws:endpoint> tag. You can also do this programmatically but why would you.
- Message and Exchange: The Message and Exchange objects have changed dramatically from XFire. CXF’s Message and Exchange objects are devoid of all those helpful methods that were present in XFire but they make up for it by having get(Class) and get(String) methods which can be used to retrieve valuable information. It’s probably a good idea to look through Exchange.keySet() and Message.keySet() and see whats available to you in your interceptors. For example when a Fault occurs, the message.get(Exception.class) returns the exception that was thrown to cause the fault. Also note that the information present in these maps varies depending on what Phase you’re in.
Now to the WS-Security example. CXF just added support for configuring interceptors using annotations which means configuring WS-Security for our web services just got easier.
Here’s the service interface and implementation.
02 |
public interface SportsService { |
03 |
public String getTeam(); |
09 |
serviceName= "SportsService" , |
10 |
endpointInterface= "ca.utoronto.sis.cxfapp.SportsService" ) |
11 |
@InInterceptors (interceptors={ |
12 |
"com.arsenalist.cxfapp.WSSecurityInterceptor" |
14 |
public class SportsServiceImpl implements SportsService { |
16 |
public String getTeam() { |
I’ve added a single in interceptor called WSSecurityInterceptor which is a class that we’ll write. In XFire we also needed a DomInHandler and a DomOutHandler for each service implementation, none of that is required here. WSSecurityInterceptor will just wrap the WSS4JInInterceptor class, the reason we can’t just specify WSS4JInInterceptor as an annotation is because we need to set custom properties on it such as using UsernameToken authentication.
The other thing WSSecurityInterceptor does is add a ValidateUserTokenInterceptor which is similar to ValidateUserTokenHandler in the XFire examples. Since WSS4J validates a UsernameToken only if it finds a security header we need to cover the case where no security header is specified. ValidateUserTokenInterceptor just makes sure the username, password, nonce and timestamp are specified before even considering it a valid request. Here’s the WSSecurityInterceptor and the PasswordHandler class:
01 |
public class WSSecurityInterceptor extends AbstractPhaseInterceptor { |
03 |
public WSSecurityInterceptor() { |
04 |
super (Phase.PRE_PROTOCOL); |
06 |
public WSSecurityInterceptor(String s) { |
07 |
super (Phase.PRE_PROTOCOL); |
10 |
public void handleMessage(SoapMessage message) throws Fault { |
12 |
Map props = new HashMap(); |
13 |
props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN); |
14 |
props.put(WSHandlerConstants.PW_CALLBACK_REF, new PasswordHandler()); |
16 |
WSS4JInInterceptor wss4jInHandler = new WSS4JInInterceptor(props); |
17 |
ValidateUserTokenInterceptor userTokenInterceptor = new ValidateUserTokenInterceptor(Phase.POST_PROTOCOL); |
19 |
message.getInterceptorChain().add(wss4jInHandler); |
20 |
message.getInterceptorChain().add( new SAAJInInterceptor()); |
21 |
message.getInterceptorChain().add(userTokenInterceptor); |
25 |
public class PasswordHandler implements CallbackHandler { |
26 |
public void handle(Callback[] callbacks) throws IOException, |
27 |
UnsupportedCallbackException { |
28 |
WSPasswordCallback pc = (WSPasswordCallback) callbacks[ 0 ]; |
29 |
if (pc.getIdentifer().equals( "arsenal" )) { |
30 |
pc.setPassword( "gunners" ); |
Note that the ValidateUserTokenInterceptor is invoked in a later phase than WSS4JInterceptor. Here’s the ValidateUsertokenInterceptor class:
01 |
public class ValidateUserTokenInterceptor extends AbstractPhaseInterceptor { |
03 |
public ValidateUserTokenInterceptor(String s) { |
07 |
public void handleMessage(SoapMessage message) throws Fault { |
08 |
boolean userTokenValidated = false ; |
09 |
Vector result = (Vector) message.getContextualProperty(WSHandlerConstants.RECV_RESULTS); |
10 |
for ( int i = 0 ; i < result.size(); i++) { |
11 |
WSHandlerResult res = (WSHandlerResult) result.get(i); |
12 |
for ( int j = 0 ; j < res.getResults().size(); j++) { |
13 |
WSSecurityEngineResult secRes = (WSSecurityEngineResult) res.getResults().get(j); |
14 |
WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) secRes |
17 |
if (!principal.isPasswordDigest() || |
18 |
principal.getNonce() == null || |
19 |
principal.getPassword() == null || |
20 |
principal.getCreatedTime() == null ) { |
21 |
throw new RuntimeException( "Invalid Security Header" ); |
23 |
userTokenValidated = true ; |
28 |
if (!userTokenValidated) { |
29 |
throw new RuntimeException( "Security processing failed" ); |
Now we have a service implementation annotated in a way where it is WS-Security enabled and is also registered as a web service. The final step remaining is to expose it as a consumable endpoint. That can be achieved by either of the following ways:
Using the fully qualified class name:
<jaxws:endpoint
id="helloWorld"
implementor="com.arsenalist.cfxapp.SportsServiceImpl"
address="/SportsService" />
Or by referring to a Spring bean corresponding to the @WebService annotated class. This would be more prudent if you’re using Dependency Injection in your service implementations.
<bean id="sportsServiceImpl" class="com.arsenalist.cfxapp.SportsServiceImpl"/>
<jaxws:endpoint
id="sportsService"
implementor="#sportsServiceImpl"
address="/SportsService" />
Finally you could also just use good ‘ol fashioned Spring beans. This comes in handy if you wan to specify a different binding like Aegis:
<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding"/>
<bean class="org.apache.cxf.frontend.ServerFactoryBean" init-method="create">
<property name="serviceBean" ref="registrationSoapService"/>
<property name="address" value="/services/1_0_0/Registration"/>
<property name="dataBinding" ref="aegisBean"/>
</bean>
The CXF documentation which shows how to configure the web.xml is pretty straightforward.
If you’re using Maven, the dependencies section of the pom.xml might look something like this. Remember that support for configuring interceptors via annotations was just added so you have to access the SNAPSHOT repositories instead of the main one.
<repositories>
<repository>
<id>apache-snapshots</id>
<name>Apache SNAPSHOT Repository</name>
<url>http://people.apache.org/repo/m2-snapshot-repository/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>apache-incubating</id>
<name>Apache Incubating Repository</name>
<url>http://people.apache.org/repo/m2-incubating-repository/</url>
</repository>
</repositories>
<dependencies>
...
<!-- spring beans, core, context, web 2.0.6 -->
...
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.1-incubator-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-core</artifactId>
<version>2.1-incubator-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>2.1-incubator-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-ws-security</artifactId>
<version>2.1-incubator-SNAPSHOT</version>
</dependency>
...
<dependencies>
Thanks for reading.
<!-- adcode-->
<script type="text/javascript"><!-- google_ad_client = "pub-3443918307802676"; google_ad_output = "js"; google_feedback = "on"; google_max_num_ads = "4"; google_ad_width = 336; google_ad_height = 280; google_ad_format = "336x280_as"; google_image_size = "336x280"; google_ad_type = "text,flash,html"; google_ad_channel ="7770228814+6875057225+7401333398+7453468586+2794543176"; var color_bg = 'ffffff'; var color_text = '000000'; var color_link = '0000ff'; var color_border = 'ffffff'; var color_url = '0000ff'; google_analytics_domain_name = "wordpress.com"; //--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script><script>google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);</script><script src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3443918307802676&format=336x280_as&output=js&h=280&w=336&image_size=336x280&lmt=1281250699&num_ads=4&channel=7770228814%2B6875057225%2B7401333398%2B7453468586%2B2794543176&ad_type=text%2Cflash%2Chtml&ea=0&feedback_link=on&flash=10.1.53&url=http%3A%2F%2Fdepressedprogrammer.wordpress.com%2F2007%2F07%2F31%2Fcxf-ws-security-using-jsr-181-interceptor-annotations-xfire-migration%2F&dt=1281250705073&shv=r20100728&correlator=1281250705074&frm=0&adk=254196587&ga_vid=2082766258.1281250704&ga_sid=1281250704&ga_hid=1260758352&ga_fc=1&ga_wpids=UA-52447-2&u_tz=480&u_his=2&u_java=0&u_h=900&u_w=1440&u_ah=870&u_aw=1440&u_cd=24&u_nplug=8&u_nmime=24&biw=1415&bih=703&ref=http%3A%2F%2Farsenalist.com%2F2007%2F07%2F31%2Fcxf-ws-security-using-jsr-181-interceptor-annotations-xfire-migration%2F&fu=0&ifi=1&dtd=15"></script>Ads by Google