February 13, 2013

Spring Security support added in Apache CXF Fediz

Initial support for Spring Security in Apache CXF Fediz added

New features are going to be added in the next version 1.1. The next feature ready for testing is the support for Spring Security for version 3.1

You can either download the sources here:

git clone git://git.apache.org/cxf-fediz.git

or

svn co https://svn.apache.org/repos/asf/cxf/fediz/trunk

or download it from the snapshot maven repository.

The Fediz Spring Plugin supports integration with the Spring Pre-Authentication scenario as described here.

A new example springPreauthWebapp has been added to the distribution to show this.

I'd like to highlight two things.

1) You can get access to the Spring Security Context like this: SecurityContextHolder.getContext().getAuthentication(); The Authentication interfaces provides the following methods.

>
MethodClassDescription
getCredentialsElementIssues Security Token (ex. SAML Assertion)
getDetailsPreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsAuthentication details like IP, Session ID
getNameStringAuthenticated user name
getAuthoritiesCollection<? extends GrantedAuthority>List of roles
getPrincipalFederationUserExtends the standard Spring User class with method getClaims()

Here is an example where the information of the Authentication object is logged:

getCredentials: [saml2:Assertion: null] getDetails: org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails@1c07a: RemoteIpAddress: 127.0.0.1; SessionId: go3xw6sxzqr5w02gn85elfgv; [ROLE_USER] getName: alice getAuthorities: [ROLE_USER] getPrincipal: org.apache.cxf.fediz.spring.FederationUser@5899680: Username: alice; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER

2) You can define rules who can access which resource as illustrated in the following snippet of applicationContext-security.xml of the new example springPreauthWebapp Please post feedback and ideas to the CXF mailing list or the JIRA task FEDIZ-38 and FEDIZ-39.

Apache CXF Fediz is a subproject of Apache CXF. Fediz helps you to secure your web applications and delegate security enforcement to the underlying application server. With Fediz, authentication is externalized from your web application to an identity provider installed as a dedicated server component. The supported standard is WS-Federation Passive Requestor Profile.

Thank you for all support and feedback!

November 26, 2012

Jetty support added in Apache CXF Fediz

Initial support for Jetty in Apache CXF Fediz added

Apache CXF Fediz is a subproject of Apache CXF. Fediz helps you to secure your web applications and delegate security enforcement to the underlying application server. With Fediz, authentication is externalized from your web application to an identity provider installed as a dedicated server component. The supported standard is WS-Federation Passive Requestor Profile.

Fediz 1.0.2 supports the following features:

  • WS-Federation 1.0/1.1/1.2
  • SAML 1.1/2.0 Tokens
  • Custom token support
  • Publish WS-Federation Metadata document
  • Role information encoded as AttributeStatement in SAML 1.1/2.0 tokens
  • Claims information provided by FederationPrincipal interface

New features are going to be added in the next version 1.1. The first feature ready for testing is the support for the Open Source Servlet Container Jetty for version 7 and 8.

You can either download the sources here:

git clone git://git.apache.org/cxf-fediz.git

or

svn co https://svn.apache.org/repos/asf/cxf/fediz/trunk

or download it from the snapshot maven repository.

As Jetty can easily be embedded in your application you might be interested to look at the Unit test for the Jetty module how to configure the FederationAuthenticator. If you download the Jetty distribution the configuration for Fediz is described here. Please post feedback and ideas to the CXF mailing list or the Jira task FEDIZ-5.

Thank you for all support and feedback!

July 31, 2012

Add End-To-End monitoring to Your CXF application with Open Source

This is the second blog I mentioned here.

I'd like to show how to add end-to-end monitoring to your CXF based applications. End-to-end monitoring means that you can follow the message flow which has been triggered by a user across several web services nodes (consumer/provider). Context information of a message and its content are pushed by every web service node to a central server component. The communication style is asynchronous to not delay message processing.

To show how this can be achieved I'll also use the example wsclientWebapp of the Apache CXF Fediz project which I already used to illustrate how to add load balancing and failover. Further information is available here.

This example already supports Web SSO (IDP), WS-Security and STS. The architecture is described in a previous blog.

A web appliation is federation enabled with Fediz to support SSO. As part of the login of the browser user, a SAML token is issued which contains the claims information which are relevant to the web application. The web application calls a web service on behalf of the logged in user. This is accomplished by the CXF STS which is shipped as part of the Fediz in the IDP/STS component. The Web Service Consumer (Web Application) requests a new token based on the WS-SecurityPolicy of the Web Service Provider on behalfof of the security token issued as part of the Web Login. In this example, the security tokens are SAML tokens.

More information on how to build, deploy and test the demo are described in the README.

This example has the following gaps to be deployed in a distributed environment:

  • URL's of the web service provider is configured on the service consumer side which is difficult to manage across the environments and for all web service consumers
  • If an error occurs you have to analyze log files of all involved nodes in the message flow to drill down the root cause of the issue. Usually, the log files of all involved applications are distributed in the network. It's difficult to correlate the messages in the different log files.
These issues might be manageable within the scope of a project but not on the enterprise level as your application might consume several services which are used by other applications as well. As mentioned at the beginning, the first gap is addressed in the previous blog. This blog will address how to add end-to-end monitoring.

Talend built Apache licensed open source components to add load balancing, failover and end-to-end monitoring to your CXF/Camel based applications. This blog shows you how easily you can integrate this component into your application.

Update your CXF application

Talend built a SAM (Service Activity Monitoring) server component where service participants (consumer/provider) can send information about incoming and outgoing messages. The SAM server is Apache licensed. Besides the server component, the SAM agent is deployed as part of the CXF application which hooks into the interceptor chain to collect all required information about the message and pushes it to the SAM server asynchronously.

What do you have to do in your application?

A) Web Service Provider

Make the following changes in the maven project wsclientWebapp/webservice/service

1) add POM dependency for the Talend SAM agent library

This library hooks into the CXF interceptor chain to send service activity information to the SAM server.

  <dependency>
    <groupId>org.talend.esb</groupId>
    <artifactId>sam-agent</artifactId>
    <version>5.1.1</version>
  </dependency>
2) add a file agent.properties to your maven project src/main/resources

This file contains information where the SAM agent is running and what kind of information should be sent.

collector.scheduler.interval=500
collector.maxEventsPerCall=10
collector.lifecycleEvent=false

log.messageContent=true
log.maxContentLength=-1
log.enforceMessageIDTransfer=false

service.url=http://localhost:8040/services/MonitoringServiceSOAP
service.retry.number=3
service.retry.delay=5000
3) Update Spring configuration file applicationContext.xml

The highlighted lines must be added to the example application.

...
   <import resource="classpath:META-INF/cxf/cxf.xml" />
   <import resource="classpath:META-INF/tesb/locator/beans.xml" />
   <import resource="classpath:META-INF/tesb/agent-context.xml" /> 
...
   <!-- GreeterService -->
   <jaxws:endpoint id="GreeterService"
      implementor="org.apache.cxf.fediz.examples.service.GreeterImpl"
      wsdlLocation="WEB-INF/wsdl/hello_world.wsdl"
      serviceName="svc:GreeterService"
      xmlns:svc="http://apache.org/hello_world_soap_http"
      address="/GreeterService">

      <jaxws:properties>
         <entry key="ws-security.signature.properties" value="stsKeystore.properties" />
         <entry key="org.talend.tesb.endpoint.secured" value="true"/>
      </jaxws:properties>

      <!-- Talend feature -->
      <jaxws:features>
         <bean class="org.talend.esb.servicelocator.cxf.LocatorFeature" />
         <ref bean="eventFeature"/>
      </jaxws:features>
   </jaxws:endpoint>
4) Run "mvn clean install"

Maven builds a new WAR package. This package is now able to send service activity information to the SAM server.

B) Web Service Consumer

Make the following changes in the maven project wsclientWebapp/webapp

1) add POM dependency for the Talend SAM agent library

This library hooks into the CXF interceptor chain to send service activity information to the SAM server.

  <dependency>
    <groupId>org.talend.esb</groupId>
    <artifactId>sam-agent</artifactId>
    <version>5.1.1</version>
  </dependency>
2) add a file agent.properties to your maven project src/main/resources

This file contains information where the SAM agent is running and what kind of information should be sent.

collector.scheduler.interval=500
collector.maxEventsPerCall=10
collector.lifecycleEvent=false

log.messageContent=true
log.maxContentLength=-1
log.enforceMessageIDTransfer=false

service.url=http://localhost:8040/services/MonitoringServiceSOAP
service.retry.number=3
service.retry.delay=5000
There are different options to configure what kind of information should be pushed to the SAM server. Please check the Talend_ESB_InfrastructureServices manual for all configuration options like:
  • Send message content
  • Configure maximum length of content to be sent
  • filters to find/replace in message content
  • add custom context information
  • ...
3) Update Spring configuration file applicationContext.xml

The highlighted lines must be added to the example application.

...
   <import resource="classpath:META-INF/cxf/cxf.xml" />
   <import resource="classpath:META-INF/tesb/locator/beans.xml" />
   <import resource="classpath:META-INF/tesb/agent-context.xml" /> 
...
  <jaxws:client id="HelloServiceClient" serviceName="svc:GreeterService"
    xmlns:svc="http://apache.org/hello_world_soap_http"
    serviceClass="org.apache.hello_world_soap_http.Greeter"
    address="locator://whatever"
    wsdlLocation="WEB-INF/wsdl/hello_world.wsdl">
    <jaxws:properties>
      <entry key="ws-security.sts.client">
        <bean class="org.apache.cxf.ws.security.trust.STSClient">
          <constructor-arg ref="cxf" />
          <property name="wsdlLocation" value="https://localhost:9443/fedizidpsts/STSServiceTransport?wsdl" />
          <property name="serviceName"
            value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}SecurityTokenService" />
          <property name="endpointName"
            value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port" />
          <property name="onBehalfOf" ref="delegationCallbackHandler" />
          <property name="enableAppliesTo" value="true" />
        </bean>
      </entry>
    <entry key="ws-security.cache.issued.token.in.endpoint" value="false" />
    </jaxws:properties>
    <jaxws:features>
      <bean class="org.talend.esb.servicelocator.cxf.LocatorFeature" />
      <ref bean="eventFeature"/>
    </jaxws:features>
  </jaxws:client>
4) Run "mvn clean install"

Maven builds a new WAR package. This package is now able to send service activity information to the SAM server.

Deploy SAM server

Last but not least, the Talend SAM server must be deployed and started which is shipped as part of the Talend ESB. Follow these steps to start the SAM server (if you have run already the demo for the Service Locator you only have to run tesb:start-all):
  1. Download the Talend ESB Standard Edition (SE) here. The Standard Edition has full functionality and is Apache licensed.
  2. Unzip the file
  3. Run <install-dir>/container/trun
  4. Execute the following command in the console

    tesb:start-all

  5. You can log the most recent logs with the command

    log:display

The SAM server (and Service Locator) are running now.

More information about the Talend ESB is available here:

Test the application

You can test the application as described in the README of the Fediz example wsclientWebapp.

Enter the URL https://localhost:8443/fedizhelloworld/secure/service.jsp and click on the button Call Service after login (User: alice, Password: ecila). This triggers a web service call.

You will also see that messages are sent to the SAM server from the service consumer and service provider:

...
Jul 5, 2012 11:21:09 PM org.talend.esb.sam.agent.collector.EventCollector sendEvents
INFO: Put events(2) to Monitoring Server.
...

You can use any DB Visualizer Tool to show the data of the messages exchanged in the web services network. In this example, the data is written to Apache Derby.

You find more information where this DB is located in Talend_ESB_InfrastructureServices in chapter 4.3.

This is not a very nice UI to see which messages are part of a flow triggered by a user. In my next blog I'll describe the Talend Administration Console (TAC) which allows to see the messages exchanged and the registered service in a graphical way.

This blog showed how easy it is to add end-to-end monitoring capabilities to your CXF application with open source components and without changing a single line of code.

July 12, 2012

Add Failover and Load balancing to Your CXF application with Open Source

In the next blogs I'd like to describe how easy it is to add other enterprise features to your existing CXF based applications. My previous blogs were always very focused on security. The enterprise features I'd like to talk are:
  • load-balancing
  • failover
  • end-to-end monitoring
In this blog, I'll address load-balancing and failover whereas end-to-end monitoring is addressed in the next blog.

The assumption is that the web services are deployed on several machines. You want to either load balance the requests among the deployed services dynamically or failover in case a service is not reachable anymore.

To show how this can be implemented I'll use the example wsclientWebapp of the Apache CXF Fediz project which has been released recently.

This example already supports Web SSO (IDP), WS-Security and STS. The architecture is described in a previous blog. More information on how to build, deploy and test the wsclientWebapp example are described in its README.

This example has the following gaps to be deployed in a distributed environment:

  • URL's of the web service is configured on the service consumer side which is difficult to manage across the environments and for all web service consumers
  • If an error occurs you have to analyze log files to drill down the root cause of the issue. Usually, the log files of all involved applications are distributed in the network. It's difficult to correlate the messages in the different log files.
These issues might be manageable within the scope of a project but not on the enterprise level as your application might consume several services which are used by other applications as well. As mentioned at the beginning, the second gap will be addressed by implementing end-to-end monitoring which is described in the next blog.

Talend built Apache licensed open source components which address the previously mentioned gaps and add load balancing and failover capabilities to your CXF application.

Update your CXF application

Service Providers register its endpoints (URL) at the Talend Service Locator and service consumer can lookup for an service endpoint (compare to DNS or UDDI). The Service Locator is Apache licensed and re-uses other proven open source projects like Zookeeper. Besides the server component, the CXF Failover/Clustering feature has been extended to integrate with the Service Locator.

What do you have to do in your application?

A) Web Service Provider

Make the following changes in the maven project wsclientWebapp/webservice/service

1) add POM dependency to Talend Locator library

This library hooks into the CXF Failover/Load Balancing functionality to integrate with the Service Locator server.

  <dependency>
    <groupId>org.talend.esb</groupId>
    <artifactId>locator</artifactId>
    <version>5.1.1</version>
  </dependency>

2) add a file locator.properties to your maven project src/main/resources

This file contains information where the Service Locator server is running.

# Configured zookeeper instances (divided by a comma if several instances uses). 
# The service locator client will pick an instance
# to connect to the service locator until a connection is established. 
locator.endpoints=localhost:2181

# Endpoint prefix property is needed because the services
# in a container where the endpoints
# are relative to the container.
endpoint.https.prefix=https://localhost:10443/fedizservice

connection.timeout=5000
session.timeout=5000
3) Update Spring configuration file applicationContext.xml

The highlighted lines must be added to the example application.

...
   <import resource="classpath:META-INF/cxf/cxf.xml" />
   <import resource="classpath:META-INF/tesb/locator/beans.xml" />
...
   <!-- GreeterService -->
   <jaxws:endpoint id="GreeterService"
      implementor="org.apache.cxf.fediz.examples.service.GreeterImpl"
      wsdlLocation="WEB-INF/wsdl/hello_world.wsdl"
      serviceName="svc:GreeterService"
      xmlns:svc="http://apache.org/hello_world_soap_http"
      address="/GreeterService">

      <jaxws:properties>
         <entry key="ws-security.signature.properties" value="stsKeystore.properties" />
         <entry key="org.talend.tesb.endpoint.secured" value="true"/>
      </jaxws:properties>

      <!-- Talend feature -->
      <jaxws:features>
         <bean class="org.talend.esb.servicelocator.cxf.LocatorFeature" />
      </jaxws:features>
   </jaxws:endpoint>
4) Run "mvn clean install"

Maven builds a new WAR package. This package is now able to register its endpoint at the service locator.

B) Web Service Consumer

Make the following changes in the maven project wsclientWebapp/webapp

1) add POM dependency to Talend Locator library

This library hooks into the CXF Failover/Load Balancing functionality to integrate with the Service Locator server.

Some transitive dependencies have to be excluded as they are already part of the fediz package which is available in the parent classloader of tomcat.

  <dependency>
    <groupId>org.talend.esb</groupId>
    <artifactId>locator</artifactId>
    <version>5.1.1</version>
      <exclusions>
        <exclusion>
          <artifactId>xmlsec</artifactId>
          <groupId>org.apache.santuario</groupId>
        </exclusion>
        <exclusion>
          <artifactId>wss4j</artifactId>
          <groupId>org.apache.ws.security</groupId>
        </exclusion>
        <exclusion>
          <artifactId>ehcache-core</artifactId>
          <groupId>net.sf.ehcache</groupId>
        </exclusion>
      </exclusions>
    </dependency>
2) add a file locator.properties to your maven project src/main/resources

This file contains the network address where the Service Locator server is running.

# Configured zookeeper instances (divided by a comma if several instances uses). 
# The service locator client will pick an instance
# to connect to the service locator until a connection is established. 
locator.endpoints=localhost:2181

connection.timeout=5000
session.timeout=5000
There are different options to configure the cache of endpoints. Please check the Talend_ESB_InfrastructureServices manual for all configuration options.

3) Update Spring configuration file applicationContext.xml

The highlighted lines must be added to the example application.

...
   <import resource="classpath:META-INF/cxf/cxf.xml" />
   <import resource="classpath:META-INF/tesb/locator/beans.xml" />
...
  <jaxws:client id="HelloServiceClient" serviceName="svc:GreeterService"
    xmlns:svc="http://apache.org/hello_world_soap_http"
    serviceClass="org.apache.hello_world_soap_http.Greeter"
    address="locator://whatever"
    wsdlLocation="WEB-INF/wsdl/hello_world.wsdl">
    <jaxws:properties>
      <entry key="ws-security.sts.client">
        <bean class="org.apache.cxf.ws.security.trust.STSClient">
          <constructor-arg ref="cxf" />
          <property name="wsdlLocation" value="https://localhost:9443/fedizidpsts/STSServiceTransport?wsdl" />
          <property name="serviceName"
            value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}SecurityTokenService" />
          <property name="endpointName"
            value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port" />
          <property name="onBehalfOf" ref="delegationCallbackHandler" />
          <property name="enableAppliesTo" value="true" />
        </bean>
      </entry>
    <entry key="ws-security.cache.issued.token.in.endpoint" value="false" />
    </jaxws:properties>
    <jaxws:features>
      <bean class="org.talend.esb.servicelocator.cxf.LocatorFeature" />
    </jaxws:features>
  </jaxws:client>
4) Run "mvn clean install"

Maven builds a new WAR package. This package is now able to lookup the endpoint at the service locator.

You can also apply the following patch to the sources of the fediz example which enables the integration with the Talend Service Locator.

Deploy Service Locator

Last but not least, the Talend Service Locator must be deployed and started which is shipped as part of the Talend ESB. Follow these steps to start the Service Locator:
  1. Download the Talend ESB Standard Edition (SE) here. The Standard Edition is Apache licensed.
  2. Unzip the file
  3. Run <install-dir>/container/trun
  4. Execute the following command in the console

    tesb:start-all

  5. You can log the most recent logs with the command

    log:display

The Service Locator is running now.

More information about the Talend ESB is available here:

Test the application

You can test the application as described in the README of the Fediz example wsclientWebapp.

Enter the URL https://localhost:8443/fedizhelloworld/secure/service.jsp and click on the button Call Service after login (User: alice, Password: ecila). This triggers a web service call where the web service consumer will lookup the service provider URL at the Talend Service Locator (and caches this information). You will see log statements like this:

...
Jul 5, 2012 11:21:08 PM org.apache.cxf.clustering.FailoverTargetSelector setStrategy
INFO: Using failover strategy org.talend.esb.servicelocator.cxf.internal.EvenDistributionSelectionStrategy@9235c2
Jul 5, 2012 11:21:08 PM org.talend.esb.servicelocator.cxf.internal.LocatorClientEnabler enable
INFO: Client enabled with strategy org.talend.esb.servicelocator.cxf.internal.EvenDistributionSelectionStrategy.
Jul 5, 2012 11:21:08 PM org.talend.esb.servicelocator.cxf.internal.LocatorTargetSelector prepare
INFO: Found address with locator protocol, mapping it to physical address.
Jul 5, 2012 11:21:08 PM org.talend.esb.servicelocator.cxf.internal.LocatorTargetSelector prepare
INFO: Using strategy org.talend.esb.servicelocator.cxf.internal.EvenDistributionSelectionStrategy.
Jul 5, 2012 11:21:08 PM org.talend.esb.servicelocator.cxf.internal.ReloadSelectionStrategy getPrimaryAddress
INFO: Get address for service {http://apache.org/hello_world_soap_http}GreeterService using strategy org.talend.esb.servicelocator.cxf.internal.EvenDistributionSelectionStrategy selecting from [https://localhost:10443/fedizservice/GreeterService] selected = https://localhost:10443/fedizservice/GreeterService
...
We removed the endpoint URL https://localhost:10443/fedizservice/GreeterService in the configuration of the service consumer. Instead a lookup at the Service Locator resolves this URL.

How can you see which services are registered at the Service Locator

You can use the Zookeeper Client shipped with the Talend ESB to access the Service Locator (Zookeeper Service) which is illustrated next:
/projects/talend/TESB_SE-V5.1.1/zookeeper/bin$ ./zkCli.sh
[zk: localhost:2181(CONNECTED) 0] ls /
[cxf-locator, zookeeper]
[zk: localhost:2181(CONNECTED) 1] ls /cxf-locator
[{http:%2F%2Fapache.org%2Fhello_world_soap_http}GreeterService]
[zk: localhost:2181(CONNECTED) 2] ls /cxf-locator/{http:%2F%2Fapache.org%2Fhello_world_soap_http}GreeterService
[https:%2F%2Flocalhost:10443%2Ffedizservice%2FGreeterService]
[zk: localhost:2181(CONNECTED) 3] 

This is not a very nice UI to see the registered services. After the blog about End-to-End monitoring I'll describe the Talend Administration Console (TAC) which allows to see the registered service and the messages exchanged in a graphical way.

This blog showed how easy it is to add failover and load-balancing capabilities to your CXF application with open source components and without changing a single line of code. I very much like the approach convention over configuration.

July 2, 2012

Apache CXF Fediz

First release of Apache CXF Fediz available

Apache CXF Fediz is a subproject of Apache CXF. Fediz helps you to secure your web applications and delegate security enforcement to the underlying application server. With Fediz, authentication is externalized from your web application to an identity provider installed as a dedicated server component. The supported standard is WS-Federation Passive Requestor Profile.

Fediz supports Claims Based Access Control beyond Role Based Access Control (RBAC).

Fediz supports the following features:

  • WS-Federation 1.0/1.1/1.2
  • SAML 1.1/2.0 Tokens
  • Custom token support
  • Publish WS-Federation Metadata document
  • Role information encoded as AttributeStatement in SAML 1.1/2.0 tokens
  • Claims information provided by FederationPrincipal interface

Release notes are available here.

For more information see:


Features to come in the upcoming releases:
  • Fediz IDP supports RP IDP use case
  • SAML Holder-Of-Key support
  • Support for encrypted SAML tokens
  • Support for Jetty Container
  • Integration with Spring Security
  • Integration with CXF JAX-RS
  • SAML-P support
Feel free to raise enhancement requests and issues here

Thank you for all support and feedback!

April 16, 2012

SSO across Web Applications and Web Services - Part IV b

This blog describes how to implement the solution described in my previous blog which you must have read before.

I'd like to structure the blog into the following sections:


I've prepared this demo to run the different components in three tomcat instances. The reason is to get closer to a real scenario.

  1. tomcat-idp

    This tomcat instance hosts the security infrastructure components which are the IDP and the STS.

    HTTPS: 9443, HTTP: 9080

  2. tomcat-rp

    This tomcat instance hosts the Web Application.

    HTTPS: 8443, HTTP: 8080

  3. tomcat-svc

    This tomcat instance hosts the Web Services provider which is usually not hosted on the same instance as the frontend.

    HTTPS: 10443, HTTP: 10080

All three tomcat instances use the same certificate tomcatkeystore.jksfor HTTPS which can be downloaded here.

The Tomcat HTTPS connector is configured in conf/server.xml. Deploy the tomcatkeystore.jks of the example project to the Tomcat root directory if the Connector is configured as illustrated:
  <Connector port="10443" protocol="HTTP/1.1"
    SSLEnabled="true"
    maxThreads="150" scheme="https" secure="true"
    keystoreFile="tomcatKeystore.jks"
    keystorePass="tompass" sslProtocol="TLS"
  />

Extend the STS...

We use the same STS instance prepared for the Web SSO. The initial set up of this STS is described in my first blog. You can find the updated sources here.

The previous STS supported only one policy which says the communication with the STS must be secured on the transport level using HTTPS (TransportBinding) and UsernameToken is used as a "SupportingToken".

We have to configure a new policy which supports the TransportBinding but doesn't enforce a UsernameToken (SupportingToken assertion is missing). The new policy is added to the wsdl file ws-trust-1.4-service.wsdl.

Right now, everybody who gets into the possession of a signed SAML token could request a new security token from the STS. This risk is mitigated using HTTPS (You could authenticate the requestor also who requests a token on behalf of someone else).


The new endpoint is configured in WEB-INF/cxf-transport.xml as illustrated here:

<jaxws:endpoint id="transportSTS2"
   implementor="#transportSTSProviderBean"
   address="/STSServiceTransport"
   wsdlLocation="/WEB-INF/wsdl/ws-trust-1.4-service.wsdl"
   xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-trust/200512/"
   serviceName="ns1:SecurityTokenService"
   endpointName="ns1:Transport_Port">
</jaxws:endpoint>
You can see all updates here.


Protect the Web Services provider...


The Web Service provider is a new component. You can find the sources of this example here. It supports a basic Web Services operation called "greetMe" with no input parameters but one output parameter. The response contains the authenticated user id which is retrieved from the JAX-WS WebServiceContext. In this use case, the authenticated user id must be the same as the one used by the browser user when login to the Web Application.

The following code snippet shows the implementation of the operation greetMe:

@Resource
    WebServiceContext context = null;

    public String greetMe() {
        LOG.info("Executing operation greetMe");
        System.out.println("Executing operation greetMe");
        if (context == null) {
           return "Unknown user";
        }
        else {
           Principal p = context.getUserPrincipal();
           if (p == null) {
             return "Principal null";
           }
           return p.getName();
        }
    }

The WSDL of the service provider contains a WS-SecurityPolicy which defines that:
  • HTTPS must be used
  • a SAML token must be sent issued by an STS
  • the SAML token is a SupportingToken
<sp:TransportBinding
 xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
 <wsp:Policy>
  <sp:TransportToken>
   <wsp:Policy>
    <sp:HttpsToken RequireClientCertificate="false" />
   </wsp:Policy>
  </sp:TransportToken>
  ...
 </wsp:Policy>
</sp:TransportBinding>
<sp:SupportingTokens
 xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
 <wsp:Policy>
  <sp:IssuedToken
   sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
   <sp:RequestSecurityTokenTemplate>
    <t:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</t:TokenType>
    <t:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer</t:KeyType>
   </sp:RequestSecurityTokenTemplate>
   ...
  </sp:IssuedToken>
 </wsp:Policy>
</sp:SupportingTokens>

The service provider trusts an STS which means that it accepts every SAML token which has been signed/issued by its trusted STS. This trust is established based on the certificate (stsstore.jks) which must be configured in the service provider in the JAX-WS property ws-security.signature.properties.

<jaxws:endpoint id="GreeterService"
   implementor="org.apache.cxf.fediz.examples.service.GreeterImpl"
   wsdlLocation="WEB-INF/wsdl/hello_world.wsdl"
   serviceName="svc:GreeterService"
   xmlns:svc="http://apache.org/hello_world_soap_http"
   address="/GreeterService">
   <jaxws:properties>
     <entry key="ws-security.signature.properties" value="stsKeystore.properties" />
   </jaxws:properties>
</jaxws:endpoint>

You must ensure to add the Maven dependencies for security and policy because the policy engine is not initialized otherwise.
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-ws-policy</artifactId>
  <version>${cxf.version}</version>
</dependency>
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-ws-security</artifactId>
  <version>${cxf.version}</version>
</dependency>

The demo is prepared to deploy the Web Service to Tomcat instance tomcat-svc using Maven.

You don't have to change the tomcat URL if you have set up a Tomcat instance with HTTP port 10080 and HTTPS port 10443. Otherwise you must update the tomcat plugin in the POM:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>tomcat-maven-plugin</artifactId>
  <version>1.1</version>
  <configuration>
    <server>myTomcat</server>
    <url>http://localhost:10080/manager</url>
    <path>/${project.build.finalName}</path>
  </configuration>
</plugin>

Add the server with username and password to your Maven settings.xml
Ensure that this user has the role "manager-script" in Tomcat as described here

Run...

mvn clean install tomcat:redeploy
I recommend to use redeploy as deploy works the first time only

You can download the published WSDL with the following url:
https://localhost:10443/fedizservice/GreeterService?wsdl


Integrate the Web SSO and Web Services stack...

The Web Application fediz-tomcat-example has been extended and slightly changed. You can find the new version here. A key change is the URL used to access the FederationServlet.
old: https://localhost:8443/fedizhelloworld/secureservlet/fed
new: https://localhost:8443/fedizhelloworld/secure/fedservlet

A simple JSP page has been added which shows the authenticated user and provides a button to call the Web Service. The Web Services is protected by the WS-SecurityPolicy which enforces a SAML token issued by its trusted STS. If the call was successfull a similar page is shown as for the federation servlet but it shows the response of the Web Services provider. The response contains the authenticated username which must be the same as the one for the authenticated user in the Web Application.

The following code snippet shows the code used to call the service provider securely. The JAX-WS proxy is instantiated by Spring and thus just read from the ApplicationContext.

Greeter service = (Greeter)ApplicationContextProvider.getContext().getBean("HelloServiceClient");
String reply = service.greetMe();
out.println("<br><b>Greeter Service Response: " + reply + "</b><p>");
There is no security related code required.

The spring configuration beans.xml contains the bean configuration for the service consumer:

<jaxws:client id="HelloServiceClient" serviceName="svc:GreeterService"
  xmlns:svc="http://apache.org/hello_world_soap_http"
  serviceClass="org.apache.hello_world_soap_http.Greeter"
  address="https://localhost:10443/fedizservice/GreeterService"
  wsdlLocation="WEB-INF/wsdl/hello_world.wsdl">
  <jaxws:properties>
    <entry key="ws-security.sts.client">
      <bean class="org.apache.cxf.ws.security.trust.STSClient">
        <constructor-arg ref="cxf" />
        <property name="wsdlLocation" value="https://localhost:9443/fedizidpsts/STSServiceTransport?wsdl" />
        <property name="serviceName"
          value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}SecurityTokenService" />
        <property name="endpointName"
          value="{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port" />
        <property name="onBehalfOf" ref="delegationCallbackHandler" />
        <property name="enableAppliesTo" value="true" />
      </bean>
    </entry>
    <entry key="ws-security.cache.issued.token.in.endpoint" value="false" />
  </jaxws:properties>
</jaxws:client>

<bean id="delegationCallbackHandler" class="org.apache.cxf.fediz.example.ThreadLocalCallbackHandler" />

The Web Application must have access to the WSDL which includes the WS-SecurityPolicy assertion. Either you have deployed this WSDL within your Web Application (see configuration wsdlLocation attribute) or you download it from the service provider at runtime (see configuration for wsdlLocation of the ws-security.sts.client). The SecurityPolicy contains an IssuedToken assertion which indicates CXF to call the STS to request a token. The STS configuration is shown above where the STSClient bean is configured at entry ws-security.sts.client.

The information in the SecurityPolicy element RequestSecurityTokenTemplate are added to the SecondaryParameters element in the request to the STS. The service consumer doesn't care about its content. Our example looks like this:

<sp:RequestSecurityTokenTemplate>
  <t:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</t:TokenType>
  <t:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer</t:KeyType>
</sp:RequestSecurityTokenTemplate>

You can find more information about the correlation of STS parameters and SAML tokens here.

If you have deployed the service provider to a Tomcat instance with another port than 10443 you must update the attribute address of the bean jaxws:client.

The key thing to bridge Web SSO and Web Services stack CXF is the property onbehalfof in the STSClient bean configuration. This property references a Java CallbackHandler implementation which provides the on-behalf-of token as a DOM element. More information about the CallbackHandler for onbehalfof can be found here.
CXF ships some out-of-the-box CallbackHandler implementations. This demo provides a custom CallbackHandler implementation called ThreadLocalCallbackHandler which provides the SAML token which has been issued by the IDP/STS during the Web login. The following additional classes are required:

  • SecurityTokenThreadLocal

    This is the thread local which contains the SAML token as a DOM element. The ThreadLocalCallbackHandler gets the SAML token from this class.

  • FederationFilter

    This servlet filter reads the SAML token from the session and adds it to SecurityTokenThreadLocal and cleans it after request processing finished

You must also ensure to add the Maven dependencies for security and policy because the policy engine is not initialized otherwise.
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-ws-policy</artifactId>
  <version>${cxf.version}</version>
</dependency>
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-ws-security</artifactId>
  <version>${cxf.version}</version>
</dependency>

You can deploy this demo with Maven to Tomcat instance tomcat-rp in the same way as for the service provider described above.

You got a bunch of information in the last two blogs and I'd say a great example to illustrate how to SSO enable your Web Applications and Web Services with only a few open source components.

Update: This example is part of the Fediz distribution.

April 12, 2012

SSO across Web Applications and Web Services - Part IV a

As promised in my first blog I talk now about Part IV where an Single Sign On (SSO) enabled Web Application integrates with Web Services in the back office. I've splitted this topic into two blogs. This one describes the design of the solution and the next one describes how to implement it.

This is a list of requirements for this application:

  • Web Application must be SSO enabled using WS-Federation
  • Role Based Access Control (RBAC) required for Web Application
  • users are managed in an LDAP directory
  • security solution integrated without programming
  • industry standards should be used (WS-SecurityPolicy, Servlet- and JAX-WS Security API)
  • Web Services are secured with SAML 2.0 to authenticate the browser user
  • Web Services trust a WS-Trust Security Token Service (STS)
  • SAML token for authentication only (SupportingToken, WS-SecurityPolicy)
  • RBAC might be required for Web services in a future release
  • Confidentiality and Integrity on transport level (HTTPS)
  • prevent man-in-the-middle attack

You might think this are a bunch of very sophisticated requirements and will cost a lot of money to implement. The answer is no. In this blog I'll introduce the architecture and design and in the next blog how to realize that with Apache CXF and Tomcat.

The following diagram illustrate the overall architecture:


The key components are the WS-Trust Security Token Service (STS) and the Identity Provider (IDP) which is part of the WS-Federation Passive Requestor Profile. If you are familiar with my previous blogs about Web SSO...

... there are no new infrastructure components required to integrate SSO with Web Services. Because the STS is used for both Web SSO and Web Services Security.

The sequence of steps can be splitted into two parts the Web login and the security for the Web Services.
The Web login starts when the user access the Web Application the first time. The Web Application redirects the browser to the IDP for authentication. The IDP transforms and delegates the request to the STS. The STS validates the user against the LDAP directory and issues a signed SAML token. The browser posts the SAML token to the Web Application which validates the token and creates the security context. This part is described in more details in the above mentioned blogs.

Role information can be accessed using standard security constraints in web.xml or using the Java Servlet API without worrying about the underlying SAML security token or accessing the LDAP directory explicitly.

The second part is the security for Web Services when the user does a step in the application which requires a call to a Web Services. The Web Services stack processes the WS-SecurityPolicy of the service provider where it is described to send a token issued by the STS. The Web Services stack sends an Issue request to the STS on behalf of the browser user. The STS validates the incoming credentials and issues the requested signed SAML token for the target Web Service. The Web Services stack caches the token and attachs it to the outgoing Web Services call. The service provider trusts the STS and can therefore validate the signed SAML token on its own.

I'd like to describe the second request to the STS in more details where the Web Services stack requests a token on behalf of the browser user. You must be in the possession of the credentials (ex. password) to request a token for the browser user - otherwise, anybody could request a token for someone else without knowing the passwort using a took like SOAPUI. The Web Application itself doesn't know the password because the authentication is externalized to the IDP. Even if the authentication had been done by the Web Application the password wouldn't have been cached by the application server for security reasons. OK, you don't possess the password but you got the signed SAML token which you can only get if you provided the credentials to the STS initially. This token must be protected on the wire when exchanged between browser and IDP, the browser and the Web Application and the Web Application and the STS. The option with the best performance is SSL/TLS.
For further confidentiality protection you could encrypt the token with the certificate of the application thus only the application is able to process the token. This is a supported feature of the CXF STS.

The SAML token is cached by the application server and is provided to the Web Services stack to request a new token when required. This use case is covered by the WS-Trust specification with the OnBehalfOf element (or ActAs) in the request to the STS. The STS validates the SAML token in the OnBehalfOf element and issues a new token based on the requirements of the Web Services which are described in its WS-SecurityPolicy document and send to the STS in the SecondaryParameters element.

There are some service calls before a request is sent to the service provider. The request to the STS is the most expensive as it might require to access some ID stores to read user attributes, roles (so called claims) to add it to the SAML token. Usually, a security token has some sort of lifetime either described in the security token itself (SAML condition) or some out-of-band agreement and known by the STS only. The WS-Trust specifiction defines the Lifetime element in the response to tell the token requestor the lifetime in a security token agnostic way. Thus, the Web Services stack just have to cache the returned security token (XML element) and the LifeTime element to prevent sending an issue request for every outgoing Web Service call.

Going through the requirements above... the solution above covers all of them.

How to implement this solution is described here