CXF WS-Security using JSR 181 + Interceptor Annotations (XFire Migration)

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.

01 @WebService
02 public interface SportsService {
03      public String getTeam();
04          return "Arsenal" ;
05      }
06 }
07  
08 @WebService (
09      serviceName= "SportsService" ,
10      endpointInterface= "ca.utoronto.sis.cxfapp.SportsService" )
11 @InInterceptors (interceptors={
12          "com.arsenalist.cxfapp.WSSecurityInterceptor"
13 })
14 public class SportsServiceImpl implements SportsService {
15  
16      public String getTeam() {
17          return "Arsenal" ;
18      }
19 }

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 {
02  
03      public WSSecurityInterceptor() {
04          super (Phase.PRE_PROTOCOL);
05      }
06      public WSSecurityInterceptor(String s) {
07          super (Phase.PRE_PROTOCOL);
08      }
09  
10      public void handleMessage(SoapMessage message) throws Fault {
11  
12          Map props = new HashMap();
13          props.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
14          props.put(WSHandlerConstants.PW_CALLBACK_REF, new PasswordHandler());
15  
16          WSS4JInInterceptor wss4jInHandler = new WSS4JInInterceptor(props);
17          ValidateUserTokenInterceptor userTokenInterceptor = new ValidateUserTokenInterceptor(Phase.POST_PROTOCOL);
18  
19          message.getInterceptorChain().add(wss4jInHandler);
20          message.getInterceptorChain().add( new SAAJInInterceptor());
21          message.getInterceptorChain().add(userTokenInterceptor);
22      }
23 }
24  
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" );
31          }
32      }
33 }

Note that the ValidateUserTokenInterceptor is invoked in a later phase than WSS4JInterceptor. Here’s the ValidateUsertokenInterceptor class:

01 public class ValidateUserTokenInterceptor extends AbstractPhaseInterceptor {
02  
03      public ValidateUserTokenInterceptor(String s) {
04          super (s);
05      }
06  
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 &lt; result.size(); i++) {
11              WSHandlerResult res = (WSHandlerResult) result.get(i);
12              for ( int j = 0 ; j &lt; res.getResults().size(); j++) {
13                     WSSecurityEngineResult secRes = (WSSecurityEngineResult) res.getResults().get(j);
14                      WSUsernameTokenPrincipal principal = (WSUsernameTokenPrincipal) secRes
15                              .getPrincipal();
16  
17                      if (!principal.isPasswordDigest() ||
18                              principal.getNonce() == null ||
19                              principal.getPassword() == null ||
20                              principal.getCreatedTime() == null ) {
21                          throw new RuntimeException( "Invalid Security Header" );
22                      } else {
23                          userTokenValidated = true ;
24                      }
25                  }
26              }
27          }
28          if (!userTokenValidated) {
29              throw new RuntimeException( "Security processing failed" );
30          }
31      }
32 }

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">&lt;!-- google_ad_client = &quot;pub-3443918307802676&quot;; google_ad_output = &quot;js&quot;; google_feedback = &quot;on&quot;; google_max_num_ads = &quot;4&quot;; google_ad_width = 336; google_ad_height = 280; google_ad_format = &quot;336x280_as&quot;; google_image_size = &quot;336x280&quot;; google_ad_type = &quot;text,flash,html&quot;; google_ad_channel =&quot;7770228814+6875057225+7401333398+7453468586+2794543176&quot;; var color_bg = 'ffffff'; var color_text = '000000'; var color_link = '0000ff'; var color_border = 'ffffff'; var color_url = '0000ff'; google_analytics_domain_name = &quot;wordpress.com&quot;; //--&gt;</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(&quot;ads_core.google_render_ad&quot;, google_handleError, google_render_ad);</script><script src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-3443918307802676&amp;format=336x280_as&amp;output=js&amp;h=280&amp;w=336&amp;image_size=336x280&amp;lmt=1281250699&amp;num_ads=4&amp;channel=7770228814%2B6875057225%2B7401333398%2B7453468586%2B2794543176&amp;ad_type=text%2Cflash%2Chtml&amp;ea=0&amp;feedback_link=on&amp;flash=10.1.53&amp;url=http%3A%2F%2Fdepressedprogrammer.wordpress.com%2F2007%2F07%2F31%2Fcxf-ws-security-using-jsr-181-interceptor-annotations-xfire-migration%2F&amp;dt=1281250705073&amp;shv=r20100728&amp;correlator=1281250705074&amp;frm=0&amp;adk=254196587&amp;ga_vid=2082766258.1281250704&amp;ga_sid=1281250704&amp;ga_hid=1260758352&amp;ga_fc=1&amp;ga_wpids=UA-52447-2&amp;u_tz=480&amp;u_his=2&amp;u_java=0&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=24&amp;u_nplug=8&amp;u_nmime=24&amp;biw=1415&amp;bih=703&amp;ref=http%3A%2F%2Farsenalist.com%2F2007%2F07%2F31%2Fcxf-ws-security-using-jsr-181-interceptor-annotations-xfire-migration%2F&amp;fu=0&amp;ifi=1&amp;dtd=15"></script>Ads by Google

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值