Oliver Wulff

Features coming in Fediz 1.2 - REST

Oliver Wulff - Mon, 01/27/2014 - 10:46
The work for Fediz 1.2 has started and introduces a bunch of new features for the IDP. This post shall introduce the new features to initiate the discussion (recommended in the CXF Dev Mailing list) now. These features become available in the new minor release. Therefore, the branch trunk is has been changed to this version. The new features are:
  • Single Logout

    The IDP supports to logout from all web applications in one click according the WS-Federation specification

  • REST interface and JPA persistence store

    Configure your IDP, its relying parties (applications) and Trusted IDPs using a REST interface and make the configuration persistent in a database instead of using Spring configuration files.

This blog focus on the new REST interface and the persistence layer using JPA.

The current release version of the IDP is configured with spring configuration files which is fine for static configurations. If you make a change to support new claims or register a new relying party (web application) you have to update the spring configuration file of the fediz-idp WAR and redeploy. Therefore, the IDP has been enhanced to provide a REST interface to manage the IDP(s), its trusted IDPs, the applications and the claims for each application as well as for the IDP. The data is persistet using JPA. The complexity of the IDP is increased due to the requirement of a database but you can also use a database like H2 or HSQL which supports to launch the database embedded. The following picture illustrates the class diagram and its relationships:

As you notice, all relationships are aggregations which means the lifecycle of application has no dependency to the claims. The relationship between application and claim is specical because depending on the relation an claim is optional or mandatory.

REST InterfaceThe classes in the above class diagram map to root level resources which are independently managed (create, read, update, delete).

Base URL: https://:/fediz-idp/services/rs Resource Claim

/claims

  • GET

      Returns all resources for Claim. This is a collection and can be filtered (see below)

      Request

      • N.A.
      Response
      • 200 (OK)

        Response Body:
        <ns2:claims xmlns:ns2="http://org.apache.cxf.fediz/">
        <ns2:claim>
        <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postal</claimType>
        </ns2:claim>
        <ns2:claim>
        <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surename</claimType>
        </ns2:claim>
        </ns2:claims>

      • 500 (Error)
  • POST

      Create a new Claim resource

      Request
      <ns2:claim xmlns:ns2="http://org.apache.cxf.fediz/">
      <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postal</claimType>
      </ns2:claim>
      Response

      • 201 (Created)

        Response Body: The created resource.

        Response Header: Location contains the URL of the created resource.

      • 500 (Error)
/claims/{claimType}
  • GET

      Get the claim with the requested claimType

      Request

      • N.A.
      Response
      • 200

        Response Body: The claim with the requested claimType

      • 500 (Error)
      • 404 (Not found)
  • PUT

      Update the claim with PathParam claimType

      Request
      <ns2:claim xmlns:ns2="http://org.apache.cxf.fediz/">
      <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postal</claimType>
      <displayName>Postal</displayName>
      </ns2:claim>
      Response

      • 204 (No Content)
      • 500 (Error)
  • DELETE

      Delete the claim with the claimType passed as PathParam

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)
Resource Application

/applications

  • GET

      Returns all resources for Application. This is a collection and can be filtered (see below)

      Request

      • N.A.
      Response
      • 200 (OK)

        Response Body:
        <applications xmlns:ns2="http://org.apache.cxf.fediz/">
        <ns2:application id="100">
        <realm>urn:org:apache:cxf:fediz:fedizhelloworld</realm>
        <role>ApplicationServiceType</role>
        <serviceDisplayName>Fedizhelloworld</serviceDisplayName>
        ...

      • 500 (Error)
  • POST

      Create a new Application resource

      Request
      <ns2:application xmlns:ns2="http://org.apache.cxf.fediz/">
      <realm>urn:org:apache:cxf:fediz:newapp</realm>
      <role>ApplicationServiceType</role>
      <serviceDisplayName>Fedizhelloworld new</serviceDisplayName>
      Response

      • 201 (Created)

        Response Body: The created resource.

        Response Header: Location contains the URL of the created resource.

      • 500 (Error)
/applications/{realm}
  • GET

      Get the application with the requested realm

      Request

      • N.A.
      Response
      • 200

        Response Body: The application with the requested realm

      • 500 (Error)
      • 404 (Not found)
  • PUT

      Update the application with PathParam realm

      Request
      <ns2:application xmlns:ns2="http://org.apache.cxf.fediz/">
      <realm>urn:org:apache:cxf:fediz:newapp</realm>
      <role>ApplicationServiceType</role>
      <serviceDisplayName>Fedizhelloworld new</serviceDisplayName>
      ...
      Response

      • 204 (No Content)
      • 500 (Error)
  • DELETE

      Delete the application with the realm passed as PathParam

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)
/applications/{realm}/claims
  • POST

      Add a relationship (aggregation) between the application realm to an existing claim

      Request
      <ns2:requestClaim xmlns:ns2="http://org.apache.cxf.fediz/">
      <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname</claimType>
      <optional>false</optional>
      </ns2:requestClaim>
      Response

      • 201 (No Content)
      • 409 (Conflict)

        If the claim is already added to the resource

      • 500 (Error)
/applications/{realm}/claims/{claimType}
  • DELETE

      Delete the relationship (aggregation) between resource Application with the realm and the Sub-Resource claim

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)
Resource TrustedIdp

/trusted-idps

  • Trusted IDP has got the same methods like the Resource Claim and Application
/trusted-idps/{realm}
  • Trusted IDP has got the same methods like the Resource Claim and Application

Resource Idp

/idps

  • IDP has got the same methods like the other resources
/idps/{realm}
  • IDP has got the same methods like the other resources
/idps/{realm}/claims
  • POST

      Add a relationship (aggregation) between the resource Idp with the realm to an existing claim

      Request
      <ns2:Claim xmlns:ns2="http://org.apache.cxf.fediz/">
      <claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname</claimType>
      </ns2:Claim>
      Response

      • 204 (No Content)
      • 409 (Conflict)

        If the claim is already added to the resource

      • 500 (Error)
/idps/{realm}/claims/{claimType}
  • DELETE

      Delete the relationship (aggregation) between resource Idp with the realm and the Sub-Resource claim

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)
/idps/{realm}/applications
  • POST

      Add a relationship (aggregation) between the resource Idp with the realm to an existing resource Application

      Request
      <ns2:Application xmlns:ns2="http://org.apache.cxf.fediz/">
      <realm>urn:org:apache:cxf:fediz:newapp</realm>
      </ns2:Application>
      Response

      • 204 (No Content)
      • 409 (Conflict)

        If the application is already added to the resource

      • 500 (Error)
/idps/{realm}/applications/{applicationRealm}
  • DELETE

      Delete the relationship (aggregation) between resource Idp with the realm and the Sub-Resource Application passed in applicationRealm

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)
/idps/{realm}/trusted-idps
  • POST

      Add a relationship (aggregation) between the resource Idp with the realm to an existing resource TrustedIdp

      Request
      <ns2:TrustedIdp xmlns:ns2="http://org.apache.cxf.fediz/">
      <realm>urn:org:apache:cxf:fediz:idp:realm-B</realm>
      </ns2:TrustedIdp>
      Response

      • 204 (No Content)
      • 409 (Conflict)

        If the trusted IDP is already added to the resource

      • 500 (Error)
/idps/{realm}/trusted-idps/{trustedIdpRealm}
  • DELETE

      Delete the relationship (aggregation) between resource Idp with the realm and the Sub-Resource TrustedIdp passed in trustedIdpRealm

      Request

      • N.A.
      Response
      • 204 (NoContent)
      • 500 (Error)

Additional features of the REST interface

  • JSON Support

    By adding .json as a suffix to the URL you can enforce to get a JSON representation back instead of the default XML representation

  • Filter entries on collections (paging)

    The query parameters start and size allow you to define (default, 0, 5)

  • Query parameter expand

    As of now, sub-resources are embedded in the response by default. But I'm considering to not return all sub-resources by default when hypermedia support is added to the REST interface. Hypermedia will return link URLs where the sub-resources can be resolved

The following example illustrates how the sub-resource Claim is embedded in the resource Application.
<ns2:application id="100" xmlns:ns2="http://org.apache.cxf.fediz/">
<realm>urn:org:apache:cxf:fediz:fedizhelloworld</realm>
...
<claims>
<ns2:requestClaim id="100">
<claimType>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname</claimType>
<description>Description for firstname</description>
<displayName>firstname</displayName>
<optional>true</optional>
</ns2:requestClaim>
The resource Application supports the values claims and all for the query parameter expand and the resource Idp supports the values claims, trusted-idps and applications. You can also send several values for the query parameter expand as illustrated in the following example:
?expand=claims&expand=applications
What is missing in the current SNAPSHOT versionThe following features are missing in the current SNAPSHOT version:
  • Single Log Out (Patch applied to JIRA request)
  • Authentication support for REST interface
  • Hypermedia support for REST interface

NoteAs you noticed, the IDP supports a collection of IDPs. This is by intention even the current version doesn't support several realms in one IDP whereas the feature is already supported by the STS. This is planned in the next release.

In smaller companies you might have only one Identity Store whereas in bigger companies you probably have more than one Identity Store. To avoid deploying each IDP realm in a different Servlet Contexts the Fediz IDP will support several IDPs in one deployment. The realms are differentiated by the URL which is addressed by property uri in the future.

TestingYou can either start the IDP standalone (Jetty Maven Plugin) or within a pre-configured Tomcat Container.

Standalone deploymentThe easiest approach to test the new IDP is checking out the sources as described in section Building here and build from the project root directory:
mvn clean install
Then run within the sub-directory services/idp the following Maven command:
mvn jetty:run-war
This command will start the Jetty container and deploy the IDP in there. The database used in HSQL and the default HTTPS port is 9443 and HTTP is 9080. You can overwrite the ports with the Maven properties idp.https.port and idp.http.port as illustrated here:
mvn jetty:run-war -Didp.https.port=8443
Tomcat DeploymentThe fediz-idp.war does NOT ship the JDBC driver JAR. Be sure to deploy it under $CATALINA_HOME/lib. If you don't update the persistence.properties the default database is HSQL. You can also define the datasource on the Container Level if you like under the JNDI name java:comp/env/jdbc/fedizDataSource.

soapUI Test After you started the IDP you can import the WADL (WADL is the counterpart of a WDSL for Web Services) which can be accessed at the following URL (assumption: you started the IDP with the defaults):
https://localhost:9443/fediz-idp/services/rs?_wadl
SummaryThe REST interface is in early stage and subject to change. It's very important to have a stable REST interface for future. As the current IDP doesn't provide a Web-UI yet, you can build your own Web-UI and use the REST interface to administer the behaviour of the Fediz IDP. Therefore, it's very important to get a stable REST interface without requiring changes in your Web-UI with each new Fediz IDP release.

Please provide feedback to the CXF Dev Mailing list to discuss the feedback in broader audience.

Categories: Oliver Wulff

Apache CXF FEDIZ 1.1.0 released

Oliver Wulff - Mon, 11/11/2013 - 20:08
The CXF community has released the new Version of Apache CXF Fediz. Fediz helps you to secure your web applications and delegate security context to the underlying application which can be used for impersonation when calling other Web Services. 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.

The following features has been added:

  • Fediz IDP supports Resource and Requestor IDP role, Home Realm Discovery Service, ...
  • SAML Holder-Of-Key supported
  • Encrypted SAML Tokens supported
  • Support for Jetty, Websphere and Spring Security 2.0/3.1
  • Publish WS-Federation Metadata document for RP and IDP

The major contribution is the refactoring of the IDP to leverage the functionality and flexibility provided by Spring Web Flow and Spring Security. I wrote about this new feature here. More details to come like customizing the signin flow, etc.

Release notes are available here.

For more information see:


Features to come in the next release:
  • Integration with CXF JAX-RS
  • SAML-P support
Feel free to raise enhancement requests and issues in the JIRA project

Thank you for all support and feedback!

Categories: Oliver Wulff

Fediz 1.1 introduces Federation across Security Domains (Part 2)

Oliver Wulff - Wed, 09/04/2013 - 23:12
In the first blog on this topic I explained how to add security domains to the Fediz STS which is based on the Apache CXF STS. This blog focuses on how to set up the Fediz IDP thus you can access an application but authenticate either against the requestor IDP of realm A or realm B.

I posted a blog some time back about WS-Federation across several companies and explained the benefits and key requirements here. I recommend to read that blog first.

Here a quick summary of the goals and requirements by introducing WS-Federation for Web Application Single-Sign-On:

  • Application doesn't care about authentication
  • Application doesn't care against which authentication system the user has been authentiated
  • Application doesn't care where the user attributes are coming from
  • Application has got a trusted relationship with a single IDP/STS instance which ensures the user is authentiated and the user attributes are provided in one syntax and semantic independent from which source they are coming from
  • Application must be able to enforce certain authentication methods (ex. strong authentication)
  • Application must be able to enforce certain user attributes in the security token

In the last blog, we've prepared the STS which is responsible to issue tokens for the two realms REALMA and REALMB. Further, the STS is able to federate between the two realms by mapping the identities (attribute type of Relationship bean configuration. This means, a person must have an identity in realm A (ex. bob) and an identity in realm B (ex. BOB). To keep it simple, the mapping is based to lowercase the username. Another option is to federate/map the claims which doesn't require that a person must have an identity in both realms. This requires more effort to set up a demo and might be provided in the future for illustration purposes, but all required functionality and extension points are available.

Notes:

  • The Fediz IDP doesn't support yet to host several realms in one WAR file. Therefore, two Servlet Containers must be set up to deploy the IDP war file.

    In B2B scenarios this won't be required anyway as the B2B partner has got an IDP attached to its realm as well as the application service provider has got an IDP attached to its realm. It might make sense in scenarios where the company itself has got more than one authentication systems in place.

  • For ease of use, the Fediz IDP and Fediz STS are deployed into the same Serlvet Container and therefore accessed with the same TCP port. Due to the fact, that the Fediz STS supports both realms in one WAR file, the Fediz STS WAR fediz-idp-sts.war is just deployed twice.

Install Apache CXF Fediz IDPThe Fediz IDP is provided as part of the subproject Fediz in Apache CXF. The new version provides the Apache Maven profile realm-a (Default) and realm-b which packages the IDP either for security domain REALM A and REALM B.

You can either download the sources of the Fediz IDP from the following location


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

or


svn co https://svn.apache.org/repos/asf/cxf/fediz/trunk
You can build the IDP for realm A with the following Maven command


mvn clean install -Prealm-a
The IDP is packaged as a WAR file at services/idp/target/fediz-idp.war

You can build the IDP for realm B with the following Maven command


mvn clean install -Prealm-b
The IDP is packaged as a WAR file at services/idp/target/fediz-idp-remote.war

Note: The WAR file and therefore the servlet context name is not fediz-idp but fediz-idp-remote. This is required because cookies are bound to the hostname (ex. localhost) and the path (ex. fediz-idp). If the servlet context is the same, cookies are overwritten between the two IDP instances. There are also other options to bound the WAR file with a specific servlet context name but this relies on the Servlet Container provider.

Last option is to download the archive from the snapshot maven repository. Keep in mind that this IDP is built with the profile realm-a. Only the following files must be updated for realm B:

  • WEB-INF/applicationContext.xml

    Change <import resource="idp-config-realma.xml" />

    to

    <import resource="idp-config-realmb.xml" />

  • WEB-INF/classes/realm.properties

    Change realm.STS_URI=REALMA

    to

    realm.STS_URI=REALMB

  • WEB-INF/web.xml

    Change <param-value>urn:org:apache:cxf:fediz:idp:realm-A</param-value>

    to

    <param-value>urn:org:apache:cxf:fediz:idp:realm-B</param-value>

Note: The built WAR files require that IDP Realm A is deployed into a Servlet Container running on port 9443 and IDP Realm B is deployed into a Servlet Container running on port 12443. If you want to change that then you must update the file WEB-INF/classes/realm.properties or at source location services/idp/src/main/resources/.

Update Relying Party (Application)I assume you have installed fedizhellworld example into a supported Serlvet Container. If not, install the fedizhellworld example based on the README.txt.

The following steps must be processed to establish the trust with the IDP Realm A:

  • Issuer URL must be Realm A (ex. https://localhost:9443/fediz-idp/federation )
  • Signer certificate of Realm A must be imported into the truststore because new certificates are used for realm A and realm B
    You can either copy the file stsstore.jks from the STS archive within WEB-INF/classes or copy the file realma.cert from the STS archive from the same location.
Run the demoYou have now deployed the IDP realm A (fediz-idp.war) into a Servlet Container listening on port 9443 and IDP realm B (fediz-idp-remote.war) into a Servlet Container listening on port 12443. Finally, the Relying Party has been updated to trust the IDP Realm A.

When you now access the fedizhelloworld application (ex. https://localhost:8443/fedizhelloworld/secure/fedservlet) you get redirected to the IDP Realm A and the following web page is shown

You can now choose in which domain you would like to authenticate. Choose the IDP in the list and click Select Home Realm. If you choose Realm B you get redirected to IDP Realm B and username/password popup is shown (use uppercase username and passwords) or IDP Realm A shows username/password popup (use lowercase username and passwords).

If you choose Realm B and enter the user ALICE and the password ECILA you finally see the user alice (lowercase) shown in the application. You know why? Exactly, the STS does the identity mapping when the REALM A is requested a SAML token for the application fedizhelloworld on-behalf-of the SAML token issued by Realm B.

Notes

  • The IDP will ask you only once to choose your home realm. The choice is stored in the cookie FEDIZ_HOME_REALM
  • If your home realm is realm B and you're successfully authenticated, the IDP realm A won't redirect you to realm B the next time, as the original SAML token of realm B is cached in realm A.
IDP ConfigurationsThe design of the IDP changed (Spring Web Flow and Spring Security), new features are implemented and thus the configuration is completely different to version 1.0. I don't want to go into too much details in this blog, instead I'll update the Apache CXF Fediz Wiki soon. Use form based loginChange the spring security configuration in WEB-INF/security-config.xml and set the following configuration:
<!--<security:http-basic />-->
<security:form-login />
Configure an additional Relying PartyThe main configuration file of the IDP is idp-config-realma.xml. This file contains configurations for the IDP, trusted IDPs and Relying Parties.

If you want to configure an additional application add a ServiceConfig bean and add it to the map services in the IDP configuration bean.
<bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
...
<property name="services">
<util:map>
<entry key="urn:org:apache:cxf:fediz:fedizhelloworld" value-ref="srv-fedizhelloworld" />
</util:map>
</property>
...

<bean id="srv-fedizhelloworld" class="org.apache.cxf.fediz.service.idp.model.ServiceConfig">
<property name="realm" value="urn:org:apache:cxf:fediz:fedizhelloworld" />
<property name="protocol" value="http://docs.oasis-open.org/wsfed/federation/200706" />
<property name="serviceDisplayName" value="Fedizhelloworld" />
<property name="serviceDescription" value="Web Application to illustrate WS-Federation" />
<property name="role" value="ApplicationServiceType" />
<property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
<property name="lifeTime" value="3600" />
<property name="requestedClaims">
<util:list>
<bean class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
<property name="claimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
<property name="optional" value="false" />
</bean>
<bean class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
<property name="claimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
<property name="optional" value="false" />
</bean>
<bean class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
<property name="claimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
<property name="optional" value="false" />
</bean>
<bean class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
<property name="claimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
<property name="optional" value="true" />
</bean>
</util:list>
</property>
</bean>
It's important that the attribute realm matches with the realm configured in the application (fediz-config.xml). The attributes tokenType, lifeTime and requestedClaims are optional. Only the protocol defined in the above bean is supported by the IDP and therefore the default value. The remaining attributes are ignored but used in the future like the Web GUI. Configure an additional Trusted IDPIf you want to configure an additional trusted IDP add a TrustedIDPConfig bean and add it to the map trustedIDPs in the IDP configuration bean.
<bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
...
<property name="trustedIDPs">
<util:map>
<entry key="urn:org:apache:cxf:fediz:idp:realm-B" value-ref="trusted-idp-realmB" />
</util:map>
</property>
...

<bean id="trusted-idp-realmB" class="org.apache.cxf.fediz.service.idp.model.TrustedIDPConfig">
<property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
<property name="cacheTokens" value="true" />
<property name="url" value="https://localhost:${realmB.port}/fediz-idp-remote/federation" />
<property name="certificate" value="realmb.cert" />
<property name="trustType" value="PEER_TRUST" /> <!-- Required for Fediz Core, Process SignInResponse -->
<property name="protocol" value="http://docs.oasis-open.org/wsfed/federation/200706" />
<property name="federationType" value="FederateIdentity" /> <!-- Required for STS Relationship -->
<property name="name" value="REALM B" />
<property name="description" value="IDP of Realm B" />
</bean>
It's important that the filename of the PEM encoded certificate is configured which has been used to sign the SAML token by the trusted IDP. The attribute name is required for informational purposes whereas the remaining attributes are ignored but used in the future like the Web GUI.


Even there is much more to say I finish this post and write about other features of the new Fediz IDP in the near future.

Please post feedback and ideas to the CXF mailing list.

Thank you for all support and feedback!

Categories: Oliver Wulff

Fediz 1.1 introduces Federation across Security Domains (Part 1)

Oliver Wulff - Tue, 09/03/2013 - 10:59
Fediz 1.1 introduces a bunch of new features like support for Jetty, Spring Security and Websphere. But a lot of effort has been put into the Fediz IDP. I'd like to thank Thierry Beucher for his valuable contributions to the new release of the Fediz IDP.

The new features are:

  • Federation Metadata

    The IDP supports publishing the WS-Federation Metadata document which allows to more easily integrate the IDP into platforms which support referencing a Metadata document. Metadata consists of the signing certificate, the provided claims, etc.

  • Spring Web Flow support

    The IDP has been refactored to use Spring Web Flow to manage the federation flow. This provides flexibility to be able to customize the IDP to company's specific requirements. The IDP is secured by Spring Security to get the benefits and flexibility of Spring Security.

  • Resource IDP and Home Realm Discovery

    This is the major new feature. The IDP is able to figure out from which security domain/realm the browser request is coming from to redirect the sign-in request to the requestor IDP which does the authentication and issues a token which is sent to the Resource IDP. The Resource IDP will then either map the principal from one security domain to the target security domain and get claims information of the mapped principal or transform the claims information and finally issue a new token for the relying party (application).

    More complex scenarios described in this blog are now possible.

In this post, I'd like to focus on the last feature which I splitted in two posts. The first one focuses on extending the STS to support more than one security domain/realm and the second on the IDP.

Install Apache CXF Fediz IDPThe Fediz STS is provided as part of the subproject Fediz in Apache CXF. The new version provides the Apache Maven profile realms which packages an STS with two security domains called REALM A and REALM B.

You can either download the sources of the Fediz STS from the following location


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

or


svn co https://svn.apache.org/repos/asf/cxf/fediz/trunk
You can build the whole project with the following Maven command


mvn clean install
The STS is packaged as a WAR file at services/sts/target/fediz-idp-sts.war

or download the archive from the snapshot maven repository.

The URL of the STS has the following syntax depending on the hostname and port of your servlet engine. https://localhost:port/fediz-idp-sts/?wsdl The page will list the different URL's for the web service endpoints of the STS:

  • https://localhost:9443/fediz-idp-sts/REALMA/STSServiceTransportUT
    STS endpoint for REALM A which requires username/password authentication
  • https://localhost:9443/fediz-idp-sts/REALMA/STSServiceTransport
    STS endpoint for REALM A with requires on-behalf-of saml token (implicit identiy mapping is done)
  • https://localhost:9443/fediz-idp-sts/REALMB/STSServiceTransportUT
    STS endpoint for REALM B which requires username/password authentication
  • https://localhost:9443/fediz-idp-sts/REALMB/STSServiceTransport
    STS endpoint for REALM B with requires on-behalf-of saml token (implicit identiy mapping is done)
In the context of federation, you request a token from your requestor STS/IDP. In this example, either REALM-A or REALM-B with username/password (.../fediz-idp-sts/<realm>/STSServiceTransportUT). After authentication, you request (implicitly as part of the federation protocol) a specific token of the security domain/realm where the application is conntected to. This use case makes use of the on-behalf-of feature of the STS (.../fediz-idp-sts/<realm>/STSServiceTransport).

The following users are set up in realm A and realm B: UserPasswordRealm AaliceecliabobbobteddetRealm BALICEECLIABOBBOBTEDDET

As you might imagine, the identity mapping implementation is fairly easy as you just lower- or uppercase the principal name. More information about how to plug in different identity mappings see below in Identity Mapper.

How to add a new security domain to the STSIf you customize the realms or add an additional realm, the following steps are required. You can either customize the deployed WAR fediz-idp-sts.war of the downloaded archive or make updates to the sources
Note: You could also make use of the Overlay feature of Apache Maven.

  • Define a new realm C

    Some beans must be updated and added to the Spring configuration file cxf-transport.xml. The changes for a new realm are highlighted in bold.

    Source location: src/realms/webapps/WEB-INF/
    Deploy location: /WEB-INF/
    <util:map id="realms">
    <entry key="REALMA" value-ref="realmA"/>
    <entry key="REALMB" value-ref="realmB"/>
    <entry key="REALMC" value-ref="realmC"/>
    </util:map>

    <bean id="realmA" class="org.apache.cxf.sts.token.realm.SAMLRealm">
    <property name="issuer" value="STS Realm A"/>
    <property name="signaturePropertiesFile" value="stsKeystoreA.properties" />
    <property name="callbackHandlerClass" value="org.apache.cxf.fediz.service.sts.PasswordCallbackHandler" />
    </bean>

    <bean id="realmB" class="org.apache.cxf.sts.token.realm.SAMLRealm">
    <property name="issuer" value="STS Realm B"/>
    <property name="signaturePropertiesFile" value="stsKeystoreB.properties" />
    <property name="callbackHandlerClass" value="org.apache.cxf.fediz.service.sts.PasswordCallbackHandler" />
    </bean>

    <bean id="realmC" class="org.apache.cxf.sts.token.realm.SAMLRealm">
    <property name="issuer" value="STS Realm C"/>
    <property name="signaturePropertiesFile" value="stsKeystoreC.properties" />
    <property name="callbackHandlerClass" value="org.apache.cxf.fediz.service.sts.PasswordCallbackHandler" />
    </bean>


    <util:list id="relationships">
    <bean class="org.apache.cxf.sts.token.realm.Relationship">
    <property name="sourceRealm" value="REALMA" />
    <property name="targetRealm" value="REALMB"/>
    <property name="identityMapper" ref="identityMapper" />
    <property name="type" value="FederatedIdentity" />
    </bean>
    <bean class="org.apache.cxf.sts.token.realm.Relationship">
    <property name="sourceRealm" value="REALMB" />
    <property name="targetRealm" value="REALMA"/>
    <property name="identityMapper" ref="identityMapper" />
    <property name="type" value="FederatedIdentity" />
    </bean>

    <bean class="org.apache.cxf.sts.token.realm.Relationship">
    <property name="sourceRealm" value="REALMA" />
    <property name="targetRealm" value="REALMC"/>
    <property name="identityMapper" ref="identityMapper" />
    <property name="type" value="FederatedIdentity" />
    </bean>

    </util:list>

    In this case, only a trust relationship from realm A to realm C is established and it's based on identity mapping.

  • Generate signing certificate

    The new realm signs the SAML assertion with a different signer certificate.
    keytool -genkeypair -keyalg RSA -validity 3600 -alias realmc -keystore stsrealm_c.jks -dname "cn=REALMC" -keypass realmc -storepass storepass
    keytool -export -keystore stsrealm_c.jks -storepass storepass -export -alias realmc -file realmc.cert
    The keystore has to be added
    Source location: src/realms/resources
    Deploy location: /WEB-INF/classes

  • Import certificate into truststore ststrust.jks

    The certificate must be added to the truststore thus another realm is able to validate the SAML assertion signed by realm C.

    Note: The above federation relationship definitions do not cover the use case that another realm must trust realm C but I recommend to add the certificate for completeness reasons.
    keytool -import -trustcacerts -keystore ststrust.jks -storepass storepass -alias realmc -file realmc.cert -noprompt
    The truststore has to be updated at
    Source location: src/realms/resources
    Deploy location: /WEB-INF/classes

  • Configure signer certificate

    Above, the signer certificate is configured for the SAML Realm C in the attribute signaturePropertiesFile of the bean realmC. The properties file has to look like this:
    org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
    org.apache.ws.security.crypto.merlin.keystore.type=jks
    org.apache.ws.security.crypto.merlin.keystore.password=storepass
    org.apache.ws.security.crypto.merlin.keystore.alias=realmc
    org.apache.ws.security.crypto.merlin.file=stsrealm_c.jks
    Note: Copy&paste an existing stsKeystore properties file.

    The properties file has to be added here:
    Source location: src/realms/resources
    Deploy location: /WEB-INF/classes

  • Define JAX-WS endpoint in STS

    Two JAX-WS endpoints are required depending on whether you need to support username/password authentication in the STS (WSDL Port TransportUT_Port) and/or issue a SAML token on-behalf-of another SAML token (WSDL Port Transport_Port).

    The former requires an authentication backend which is file based in the Fediz STS. The file based authentication backend relies on the UsernamePasswordCallbackHandler which uses a spring map with user name and password entries (see beans upCallBackHandlerRealmC and REALMC).
    <jaxws:endpoint id="transportSTSRealmC" implementor="#transportSTSProviderBean"
    address="/REALMC/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:properties>
    </jaxws:properties>
    </jaxws:endpoint>

    <jaxws:endpoint id="transportSTSRealmCUT" implementor="#transportSTSProviderBean"
    address="/REALMC/STSServiceTransportUT" 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:TransportUT_Port">
    <jaxws:properties>
    <entry key="ws-security.callback-handler" value-ref="upCallBackHandlerRealmC" />
    </jaxws:properties>
    </jaxws:endpoint>

    <bean id="upCallBackHandlerRealmC"
    class="org.apache.cxf.fediz.service.sts.UsernamePasswordCallbackHandler">
    <property name="passwords" ref="REALMC" />
    </bean>

    <util:map id="REALMC">
    <entry key="user1"
    value="pw1" />
    </util:map>
    The bean which defines the username and passwords is defined in the imported spring configuration file passwords.xml. The claims of the users in the two realms are defined in userClaims.xml. You can find more information about managing the claims in an older blog.

    If you want to configure an LDAP backend check the following blog post:

  • Identity mapper

    If you add a new realm, the Identity Mapper provided in org.apache.cxf.fediz.service.sts.realms.IdentityMapperImpl must be enhanced. In practise, you access a database, LDAP or web service to get the mapping. You must implement the interface org.apache.cxf.sts.IdentityMapper to customize the identity mapping to your needs.

Customize realm concept
  • The Fediz STS is based on the Apache CXF STS. The STS supports several realms where each realm is connected to an authentication server like LDAP, file (Testing), database or a custom authentication server. The service consumer must know from which STS realm he requests a token from by choosing the appropriate URL. The distinction is based on the syntax in the URL.

    The syntax in the Fediz STS is https://:/fediz-idp-sts/<REALM>/.... The distinction is after the servlet context fediz-idp-sts. This behaviour is implementd in org.apache.cxf.fediz.service.sts.realms.UriRealmParser and configured in the bean customRealmParser.

    You can implement a different distinction based on the machine name, http port or servlet context. Maybe you prefer to deploy the realms in different JVMs. You just have to implement the interface org.apache.cxf.sts.RealmParser.

  • When you request a token on-behalf-of another SAML token, the STS must be able to figure out from which realm the token has been issued. As above, the STS provides an interface which must be implement to change the default behaviour of the Fediz STS. The default behaviour is implemented in org.apache.cxf.fediz.service.sts.realms.SamlRealmCodec and expects the realm encoded in the CN (Common Name) of the signer certificate. This class implements the interface org.apache.cxf.sts.token.realm.SAMLRealmCodec and can be customized. You have to update the bean samlRealmCodec or update the bean which references this bean.

Please post feedback and ideas to the CXF mailing list.

Thank you for all support and feedback!

Categories: Oliver Wulff

Logging in Apache CXF STS enhanced

Oliver Wulff - Tue, 05/21/2013 - 15:00
This extension will be available in CXF release 2.7.6 which is not yet available. But you can run tests with the SNAPSHOT build till this version is released. Please provide feedback to the CXF mailing list.

Different logging frameworks (SLF4J, Log4J, Logback, JUL) can be used to log events for Apache CXF STS. The configuration allows to define which logger should log messages till to which log level. That works fine to drill down generic issues but it doesn't help too much to know whether a certain user could successfully log in or had any specific issues. Further, the WS-Trust interface is very generic. Therefore, the same user can request tokens but for different applications using different credential types. If a log in error occurs some context information is required to easily drill down user specific issues.

Based on the experience of a customer deployment, the following information is helpful to figure out how often a user requested a token and under which circumstances:

  • AppliesTo
    For which application did the user request a token
  • Source IP
    From which machine did the application request a token for a user
  • Claims
    Which claims did the user request for an application
  • Security Header
    How did the user try to log in (Username/password, Kerberos, X509, ...)
  • Realm
    For which security domain did the user request a token
  • etc.
All this information are available within the core classes of the STS and thus not customizable without patching these classes. The next release of CXF will provide a customizable logging/auditing functionality to fulfill various requirements. Spring EventingThe Spring framework provides an eventing mechanism which is designed for simple communication between Spring beans. Instead of introducing a new eventing mechanism to push data to a class which processes the data and writes it to a log file the new feature leverages the usage of the Spring framework in the CXF STS. How Spring eventing works is described on the following blog. If you don't want to delay STS related processing you can publish the events asynchronously which is described here. CXF STS custom Application EventsDepending on the STS operation called, a different object with context information is created in the CXF STS. The following table summarizes the defined bindings in the WS-Trust specification, the CXF related context object as well a link with more information about this binding:

BindingContext objcectSpring EventDocumentationIssueTokenProviderParametersSTSIssueSuccessEvent
STSIssueFailureEventblogValidateTokenValidatorParametersSTSValidateSuccessEvent
STSValidateFailureEventblogCancelTokenCancellerParametersSTSCancelSuccessEvent
STSCancelFailureEventblogRenewTokenRenewerParametersSTSRenewSuccessEvent
STSRenewFailureEventblog

The different binding implementations support the interface ApplicationEventPublisherAware thus they can publish events about a successful or failed request. You have to provide an implementation of ApplicationListener to listen to Spring Application Events. Due to the usage of generics you can specify which events you want to listen to. All the above STS specific events inherit the abstract class AbstractSTSEvent. If you want to listen to all STS events then you must provide an implementation like this:
public class AllSTSEventsListener implements ApplicationListener {
@Override
public void onApplicationEvent(AbstractSTSEvent event) {
// do whatever you want here
}
}
If you want to listen to all successful issue events you must use the generic STSIssueSuccessEvent. The STS provides the LoggerListener which listens to all STS events and uses the CXF Logging API to write the log message. All you have to do is configure the following bean in the STS application context configuration (ex. cxf-transport.xml):
<bean id="loggerListener" class="org.apache.cxf.sts.event.LoggerListener" />

If you want to configure another Application listeners, just add a bean configuration and you're done.

The LoggerListener is able to log the following context information:

  • TIME
    Creation time of the event
  • OPERATION
    STS binding/operation
  • WS_SEC_PRINCIPAL
    Principal in WS-Security token
  • STATUS
    Successful/failed request
  • DURATION
    Processing time
  • TOKENTYPE
    Token type requested (SAML 1.1, SAML 2.0, etc)
  • REALM
    Security domain
  • APPLIESTO
    Application for which token is requested
  • CLAIMS
    Claims requested
  • ACTAS_PRINCIPAL
    Principal of ActAs token
  • ONBEHALFOF_PRINCIPAL
    Principal of On-Behalf-Of token
  • VALIDATE_PRINCIPAL
    Principal of Validate token
  • CANCEL_PRINCIPAL
    Principal of Cancel token
  • RENEW_PRINCIPAL
    Principal of Renew token
  • REMOTE_HOST
    Hostname/IP which requested the token
  • REMOTE_PORT
    Source Port which requested the token
  • URL
    STS URL used to request token
The LoggerListener provides the following properties to customize its behaviour:

NameTypeMandatoryDefaultDescriptionlogFieldnameBooleanNoNoShould the fieldname be logged, ex. OPERATION=issuedateFormatStringNogetDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM)Format of the datelogLevelStringNoFINEWhich log level should be used?logStacktraceBooleanNoNoIn case of an error, shall the stacktrace be logged?fieldOrderList<String>NoTIME
STATUS
DURATION
REMOTE_HOST
REMOTE_PORT
OPERATION
URL
REALM
WS_SEC_PRINCIPAL
ONBEHALFOF_PRINCIPAL
ACTAS_PRINCIPAL
VALIDATE_PRINCIPAL
CANCEL_PRINCIPAL
RENEW_PRINCIPAL
TOKENTYPE
APPLIESTO
CLAIMS
EXCEPTIONOrder of context fields to be logged

If you want that all LoggerListener related log messages are written into a different file (ex. audit.log) I highly recommend to not use Java Util Logging as it's not so easy to configure a dedicated handler/appender for one logger.

  1. Configure Log4J as the logging framework in CXF (see here)
  2. Add the log4j dependency to your POM
  3. Configure the logger and appender

    log4j.rootLogger=INFO, CONSOLE, LOGFILE
    log4j.logger.org.apache.cxf.sts.event.LoggerListener=DEBUG, AUDIT

    # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.Threshold=INFO
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n

    # AUDIT is set to be a File appender using a PatternLayout.
    log4j.appender.AUDIT=org.apache.log4j.FileAppender
    log4j.appender.AUDIT.File=${catalina.base}/logs/audit.log
    log4j.appender.AUDIT.Append=true
    log4j.appender.AUDIT.Threshold=DEBUG
    log4j.appender.AUDIT.layout=org.apache.log4j.PatternLayout
    log4j.appender.AUDIT.layout.ConversionPattern=%m%n
The audit log file looks like this if configured as above:
5/10/13 8:59:59 AM;SUCCESS;2839ms;127.0.0.1;57378;Issue;https://localhost:9443/fediz-idp-sts/STSService;null;alice;null;null;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0;https://localhost:8081/doubleit/services/doubleittransportsaml1claims;null;null;

Enjoy.

Categories: Oliver Wulff

LDAP support enhanced for CXF STS 2.7.5

Oliver Wulff - Tue, 05/14/2013 - 22:45
I described in a previous blog how to configure the CXF STS for an LDAP directory for authentication and to retrieve user claims (attributes). The new release 2.7.5 of CXF provides extended support for roles managed in a LDAP directory. In previous versions, the LdapClaimsHandler added groups as roles if the groups were assigned to a multi-value attribute of the user. The new release provides an LdapGroupClaimsHandler which supports the case where an attribute of the groups lists the users who belong to this group. Further, it introduces the semantic of an application role. A user might have the role "User" for application X and role "Manager" and "User" for application Y.

The STS provides the semantic of an application with the AppliesTo parameter which is a URI. If you request a SAML token which includes the roles for a specific application (ex. MyApp), you get User and Manager back. A mapping is required in the STS to map the AppliesTo URI (URL or URN) to a String value like MyApp.

The sub-project Fediz provides in 1.1 (not released yet) a Maven profile to build the STS with an LDAP backend (instead of managing users/claims in a file). You can have a look at the ldap.xmlhere. The following configuration configures the LdapClaimsHandler and LdapGroupClaimsHandler. There is nothing special for the LdapClaimsHandler. The LdapGroupClaimsHandler also uses the Spring LdapContextSource and LdapTemplate.
<util:list id="claimHandlerList">
<ref bean="userClaimsHandler" />
<ref bean="groupClaimsHandler" />
</util:list>

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="ldap://localhost:389/" />
<property name="userDn" value="uid=admin,ou=system" />
<property name="password" value="secret" />
</bean>

<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
</bean>

<util:map id="claimsToLdapAttributeMapping">
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
value="givenName" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"
value="sn" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
value="mail" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country"
value="c" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode"
value="postalCode" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress"
value="postalAddress" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"
value="town" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/stateorprovince"
value="st" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender"
value="gender" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth"
value="dateofbirth" />
<entry key="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role"
value="member" />
</util:map>

<bean id="userClaimsHandler" class="org.apache.cxf.sts.claims.LdapClaimsHandler">
<property name="ldapTemplate" ref="ldapTemplate" />
<property name="claimsLdapAttributeMapping" ref="claimsToLdapAttributeMapping" />
<property name="userBaseDN" value="ou=users,dc=fediz,dc=org" />
<property name="userNameAttribute" value="uid" />
</bean>

<util:map id="appliesToScopeMapping">
<entry key="urn:org:apache:cxf:fediz:fedizhelloworld"
value="Example" />
</util:map>

<bean id="groupClaimsHandler" class="org.apache.cxf.sts.claims.LdapGroupClaimsHandler">
<property name="ldapTemplate" ref="ldapTemplate" />
<property name="userBaseDN" value="ou=users,dc=fediz,dc=org" />
<property name="userNameAttribute" value="uid" />
<property name="groupBaseDN" value="ou=groups,dc=fediz,dc=org" />
<property name="appliesToScopeMapping" ref="appliesToScopeMapping" />
</bean>

<jaxws:endpoint id="transportSTS1" implementor="#transportSTSProviderBean"
address="/STSService" 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:TransportUT_Port">
<jaxws:properties>
<entry key="ws-security.ut.validator">
<bean class="org.apache.ws.security.validate.JAASUsernameTokenValidator">
<property name="contextName" value="LDAP" />
</bean>
</entry>
</jaxws:properties>
</jaxws:endpoint>
I've highlighted the important beans to support the mapping of groups to (application) roles. The bean LdapGroupClaimsHandler has got the following attributes:

NameMandatoryDefaultDescriptionldapTemplateYesN.A.The Spring LDAP templategroupBaseDNYesN.A.The base group context where the search startsgroupObjectClassNogroupOfNamesObject class for groups. Used for search filter.groupMemeberAttributeNomemberThe group attribute where the list of users are storedgroupURINohttp://schemas.xmlsoap.org/ws/2005/05/identity/claims/roleThe SAML attribute name where the roles should be storedgroupNameGlobalFilterNoROLEDefault uses the CN of the group as role namegroupNameScopedFilterNoSCOPE_ROLEDefault cuts the SCOPE and the underscore of the CN of the groupappliesToScopeMappingNoN.A.The mapping is required if application specific roles must be supporteduserNameAttributeNocnUser id attribute. Only required if LDAP is not used for authentication and thus the DN of the user must be resolved first. Used for search filter.userObjectClassNopersonObject class for users. Only required if LDAP is not used for authentication and thus the DN of the user must be resolved first. Used for search filter.

The bean appliesToScopeMapping defines the mapping of the URI in the AppliesTo variable to a Name as URI's are not valid within a CN of an LDAP group.

One example for the usage of groupNameScopedFilter. One more example. Let's assume you use the same LDAP directory for the application environemnt development and pre-production and defines the following naming convention for application roles:
DEV_&ltApplication&gt_&ltROLE&gt_Group and UAT_&ltApplication&gt_&ltROLE&gt_GroupThe groupNameScopedFilter will look like this DEV_SCOPE_ROLE_Group (assumption: Different STS instances are deployed for development and pre-production).

The following table lists a few group examples and how the role value will look like in the SAML attribute. The assumption is that the AppliesTo element is urn:org:apache:cxf:fediz:fedizhelloworld which maps to the scope Example (see configuration example above) and the groupNameScopedFilter is configured like DEV_SCOPE_ROLE_Group:

Group CNRole nameDEV_Example_User_GroupUserDEV_Example_Admin_GroupAdminDEV_Example2_User_GroupignoredUAT_Example_User_GroupignoredINFR_Citrix_Accessignored

Last but not least I'd like to comment the default value of userNameAttribute which is CN. As per recommendation (5.4) the CN is typically the person's fullname and therefore doesn't fit for the user id (login name). Due to the reason that the LdapClaimsHandler had the cn as default value I wanted to keep that in sync and change it in the next non-patch release of CXF.

If you face issues or like more functionality send a message to the CXF mailing list or open a JIRA issue.

Categories: Oliver Wulff

Full Spring Security Support in Apache CXF Fediz

Oliver Wulff - Mon, 04/22/2013 - 13:39
Full Spring Security Support in Apache CXF Fediz

New features are going to be added in the next version 1.1 of Fediz. I described here how to configure the new Fediz plugin for Spring Security with Container Managed Security (Pre-Authentication in Spring Security terms). The current snapshot version of Fediz 1.1 provides also full/native Spring Security support which means the Servlet Container runs unauthenticated (no security constraints defined in web.xml) and Spring Security enforces authentication.

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.

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

As in the Pre-Authentication case, the application can get access to the Spring Security Context like this: SecurityContextHolder.getContext().getAuthentication(); The Authentication object is of instance FederationAuthenticationToken provides the following methods.

MethodClassDescriptiongetCredentialsElementIssues Security Token (ex. SAML Assertion)getDetailsWebAuthenticationDetails>Authentication details like IP, Session IDgetNameStringAuthenticated user namegetAuthoritiesCollection&lt? extends GrantedAuthority&gtList of rolesgetUserDetailsFederationUserExtends the standard Spring User class with method getClaims()

You can get more information from the Fediz Wiki how to configure Spring Security or have a look at the example here. The example shows how to configure Fediz for Spring Security and how to use the Spring Security API in your application code. Please post feedback and ideas to the CXF mailing list or the JIRA task 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!

Categories: Oliver Wulff

SSO and Fine Grained Authorization in the Cloud

Oliver Wulff - Mon, 03/04/2013 - 15:27
In February 2013, I was at ApacheCon NA 2013 in Portland, Oregon, US where I learned a lot about several Apache projects.

My presentation was about SSO and Fine Grained Authorization in the Cloud. I gave an introduction about application security 10-15 years ago and how to address challanges with Cloud deployment using Apache CXF Fediz.

Here are the slides from my talk:

ApacheCon 2013 SSO and Fine Grained Authorization in the Cloud from Oliver Wulff

Categories: Oliver Wulff

Spring Security support added in Apache CXF Fediz

Oliver Wulff - Wed, 02/13/2013 - 21:35
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.

MethodClassDescriptiongetCredentialsElementIssues Security Token (ex. SAML Assertion)getDetailsPreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails>Authentication details like IP, Session IDgetNameStringAuthenticated user namegetAuthoritiesCollection&lt? extends GrantedAuthority&gtList of rolesgetPrincipalFederationUserExtends 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!

Categories: Oliver Wulff

Jetty support added in Apache CXF Fediz

Oliver Wulff - Mon, 11/26/2012 - 20:51
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!

Categories: Oliver Wulff

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

Oliver Wulff - Tue, 07/31/2012 - 10:03
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 applicationTalend 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 serverLast 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 applicationYou 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.

Categories: Oliver Wulff

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

Oliver Wulff - Thu, 07/12/2012 - 22:07
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 applicationService 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 LocatorLast 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 applicationYou 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 LocatorYou 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.

Categories: Oliver Wulff

Apache CXF Fediz

Oliver Wulff - Mon, 07/02/2012 - 08:12
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!

Categories: Oliver Wulff

SSO across Web Applications and Web Services - Part IV b

Oliver Wulff - Mon, 04/16/2012 - 14:21
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:redeployI 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.

Categories: Oliver Wulff

SSO across web applications and web services - Part IV a

Oliver Wulff - Thu, 04/12/2012 - 16:50
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 an 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 access 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 web service 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 web service. The web services stack caches the token and attachs it to the outgoing web services call. The web services provider trusts the STS and can therefore validate the signed SAML token on its own.

I'd like to describe in more details the second request to the STS 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 - therefore we use SSL. 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 a bunch of requests before a request is sent to the web service. 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.

Stay tuned for the next blog next week where I describe how to implement it with Apache CXF.

Categories: Oliver Wulff

Packaged Tomcat Instances for Federation/SSO

Oliver Wulff - Thu, 03/08/2012 - 21:44

I've created a ZIP archive which contains two tomcat setups for the replying party (secured web application) and the identity provider (IDP). It's much easier to start with this approach and make the experience how easily a web application can be SSO enabled using SAML tokens according to the Passive Requestor Profile of WS-Federation specification.

You can download the package here.

Installation

Unzip the downloaded archive which contains in each sub-directory a dedicated tomcat instance. The two tomcat instances are described below.


tomcat-idp

Start the Tomcat container:
tomcat-idp/bin/startup.sh (or startup.bat for windows)

Mar 8, 2012 8:59:13 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-9080"]
Mar 8, 2012 8:59:13 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-9443"]
Mar 8, 2012 8:59:13 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 4245 ms

The Tomcat IDP instance creates an HTTPS listener (9443) and HTTP listener (9080). The insecure port is used for remote deployment during the maven build.

This tomcat instance has got two WAR files deployed: fedizidp and fedizidpsts.
You can find more information how to build and deploy the corresponding package here:


tomcat-rp

start the Tomcat container:
tomcat-rp/bin/startup.sh (or startup.bat for windows)

Mar 8, 2012 9:00:05 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 8, 2012 9:00:05 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8443"]
Mar 8, 2012 9:00:05 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2840 ms

The Tomcat RP instance creates an HTTPS listener (8443) and HTTP listener (8080). The insecure port is used for remote deployment during the maven build.

This tomcat instance has got one WAR file deployed: fedizhelloworld
You can find more information how to build and deploy the package here:



Test

Enter the following URL in the browser:

https://localhost:8443/fedizhelloworld/secureservlet/fed

to access the web application which redirects to the IDP component. The IDP challenges the browser to enter username/password. Next, the IDP/STS issues the SAML token which contains all requested claims information and "redirects" the browser back to the application.

This post describes how to test the fedizhelloworld application. The configured users and their claims are described here.



Secure your own web application

Follow these steps to secure your own web application:

  • If it is another Tomcat instance than tomcat-rp ensure to deploy the federation plugin into this tomcat instance as described here
  • Configure the Tomcat Valve FederationAuthenticator in your META-INF/context.xml or Tomcat server.xml as described here
  • Configure the URL of your web application (including the servlet context name) in the RPClaims.xml (bean realm2ClaimsMap) in &lttomcat-idp&gt/webapps/fedizidp/WEB-INF/RPClaims.xml and update the claims if required
  • You can manage the claims of the users in &lttomcat-idp&gt/webapps/fedizidpsts/WEB-INF/userClaims.xml
Categories: Oliver Wulff

WS-Federation across several companies

Oliver Wulff - Wed, 03/07/2012 - 21:32
I described a simple scenario about the WS-Federation Passive Requestor Profile in my previous blogs:
Before I describe a more complex scenario, I'd like to summerize the benefits of the simple scenario:
  • Authentication is externalized to IdP/STS
  • New IdP authentication mechanism can be used by all applications
  • Role Based Access control (RBAC) supported in applications
  • Claims/Attrribute based acess control (ABAC) supported in applications
  • IDP and applications deployable in different networks (ex. on-premise and cloud)
  • Easy testing with Mock IdP


Federation with B2B partners in the internet

In most cases, a web application is built for a single user group like internal users with some basic authentication mechanism like username/password against an LDAP system. Over time, the business see some potential to grow in providing this solution to partners. The application is enhanced to support a new kind of authentication mechanism for the users of the partner. The next partner has again a different kind of approach for authentication which must be extended in your application. Very often, the userids of the partner's employees have to be managed within your ID system also. What happens of an employee of the partner leaves the company? Usually, a manual process must be triggered to deprovision the user in your ID system.



How can federation and claims based authorization help here. The simple scenario doesn't support different kind of "user groups". But it's very important to highlight that the authentication mechanism is not tight into the application but instead into the IDP component. The benefit of federation is that you can integrate new partners without having an impact on your application. Just imagine how agile your application is to generate new business with new B2B partners without building a new authentication mechanism within all your applications.


How does this work? Let's look at a concrete example.


Our federation enabled web application should be provided to two new partners (fabrikam.com and adatam.com).


The users of fabrikam.com and adatam.com are managed within their own identity store. The following list provides more context information of the companies:
  • mycompany.com
    - 10000 users
    - five roles (user, manager, sales, accountmanager, admin)
  • adatam.com
    - IDP supported
    - 2000 users
    - three roles (employee, manager, administrator)
  • fabrikam.com
    - IDP supported with restrictions (SAML token contains user only)
    - 50 users
    - two roles (user, accountmanager)
The three companies have their own kind of naming for roles but the application must not differentiate between the different kind of role semantic.
fabrikam.com supports an IDP but can't provide the role information. mycompany.com decides to manage the 50 users and its roles within a dedicated ID store within their network (another option would have been to choose a more advanced IDM solution in the cloud). The usernames are different within the ID store at fabrikam.com and the dedicated ID store of mycompany.com due to different naming conventions in place.


The following deployment diagram illustrates the solution:




I haven't drawn any lines between the browser and the relying party which is the first component the browser accesses. The relying party redirects the browser to the RP-IDP (resource IDP) where the home realm discovery mechanism redirects the browser to its (requestor) IDP. The requestor IDP authenticates the browser and issues a SAML token with claims information. The browser sends the SAML token to the RP-IDP which transforms the SAML token into a format which can be validated and processed by the application (RP). This SAML token has the exact same structure independent who the requestor IDP was.


adatam.com 
What happens with the different kind of syntax of the roles?
The RP-IDP transforms the roles from the requestor IDP to the internal set of roles.
  • employee -> user
  • manager -> manager
  • administrator -> admin
fabrikam.com
How can the RP-IDP get the roles of the users?
The RP-IDP maps the userid of fabrikam.com to an internal userid in mycompany.com. The mapped userid is used to retrieve the role information. The roles/claims are not transformed.


mycompany.com
Nothing changes.


Finally, the issued tokens by the RP-IDP have the same syntax and semantic independent whether a user from fabrikam.com, adatam.com or an internal user accesses the application.


There are different kind of relationships between mycompany.com and the partner adatam.com and fabrikam.com. The former relies on federating the claims information whereas the latter federates/maps the userid/identity.




Support for identity mapping and claims transformation in STS


The STS is the key component in the WS-Federation based solution who issues the security tokens. The CXF STS supports identity mapping in the release 2.5.x.


I've finished my work to add support for claims transformation in the CXF STS.

Soon, I'll provide more details how to configure an STS with several realms (security domains) and different federation relationships among them.
Categories: Oliver Wulff

SAML sender-vouches use case

Oliver Wulff - Tue, 03/06/2012 - 07:45
In my previous blog here I described the different SAML subject confirmation methods (SCM) and how they integrate with an STS. This blog describes the use case for the Sender-Vouches (SV) SCM. As this use case can be solved with an STS also, I compare the two approaches finally.


Use case for SAML Sender-Vouches



The SAML token profile states that the attesting entity is different from the subject. You have such kind of a scenario where a web service proxy/gateway (intermediary) is deployed between your service consumer and service provider. The proxy is the attesting entity and vouches for verification (or authentication) of the subject (service consumer). The proxy signs the SAML token and the soap body to protect against modification by another party.

The following picture illustrate the deployment diagram of this intermediary pattern:


(This kind of intermediary pattern is often refered as an ESB)

The characteristic of the intermediary is that TCP connections (HTTP) are terminated and new connections are established between the intermediary and the service providers (the term proxy is widely used for settings in your OS or browser which supports HTTP tunneling).


The service provider must not accept a SAML SV token unless the token and the SOAP message content being vouched for are protected by the intermediary (attesting entity) who is trusted by the service provider. The protection can be achieved by using XML signature in the WS-Security header which signs the SAML token and the SOAP body. A direct trust is established between service provider and intermediary (service consumer).


The usage of XML signature has a significant performance impact as most XML security libraries are DOM dependent which means you need an full in-memory representation of the SOAP message. This breaks streaming (StAX parser) and increases memory usage by factors of the original message size. Another issue to consider is the potential lack of support for the STR Dereference transform algorithm  to build the signature (this was not supported two years ago in .NET).
(Apache CXF/WSS4J 2.0 is going to support streaming based XML signature and encryption in the near future)


The OASIS WS-SecurityPolicy Examples specification describes in 2.3.1.2 a more performant approach. Instead of signing the SOAP message on the XML level it uses mutual SSL handshake where the service provider requires that the intermediary has configured a client certificate for the HTTPS communication he trusts. The side effect is that this won't be supported by all web services stack and you run into interoperability issues.


SAML SV works fine if the service provider, the intermediary and service consumer are in the same security domain which means that the principal name "jdoe" is processable in all of them. 
  • If the service providers are in different security domains how shall the intermediary map/federate the identity? 
  • If the service provider should support more than one security domain how should the intermediary encode the security domain information into the SAML token? 
  • Do the different web services stack of your service providers support the same kind of mechanism to decode security domain information or do you have to write code for all your stacks to support that? 
  • If the service provider requires role information in the SAML token how should the intermediary retrieve that and encode within the SAML token?
  • Do the web services stacks of your service providers support the same kind of mechanism to decode role information thus you can use container managed role based access control?
  • Are the issued security tokens/retrieved authorization information cached?
  • If the service provider requires specific claims information in the SAML token ...
As you can see, you have to consider a few things before deciding to go with SAML Sender-Vouches subject confirmation method.

If your enviroment can fulfill the following requirements you can consider using SAML Sender-Vouches:
  • there is only one security domain
  • you don't have to authorize your web services and thus don't need additional claims in the token
  • you have only one java and .NET web services stack
  • size of soap messages are small
  • performance is not critical or business logic related processing time is much, much higher
OK, you see that SAML Sender-Vouches is not my favourite subject confirmation method. The main reasons are the underlying pattern of a direct trust (administration effort, comparable to the usage of self-signed certificates without a certificate authority) and lots of functionality described above belongs to an IDM solution which is a dedicated component which can be integrated into different kind of contexts (Web Services, Web SSO, B2B gateway, ...).
Is there another solution to address the intermediary case?



Use case "Intermediary" for WS-Trust Security Token Service

The answer to the question in my last paragraph is yes.


The WS-Trust specification defines two ways to address it:
  • OnBehalfOf
  • ActAs
The following blog post provides more information about the differences of OnBehalfOf and ActAs. In both cases, the security token received by the intermediary is sent within one of these elements in the request (RST) to the STS. The STS validates the security token and issues a new one with the information of the original principal.


Is there a standard mechanism to tell the intermediary that the service provider requires a token issued by an STS?
Yes, the service provider's WS-SecurityPolicy defines an IssuedToken assertion.

Is there a standard mechanism to tell the intermediary what kind of security token (saml1, saml2, other) the service provider requires?
Yes, the service provider's WS-SecurityPolicy defines the TokenType in the RequestSecurityTokenTemplate of the IssuedToken assertion.

Is there a standard mechanism to tell the intermediary from which security domain the service provider requires a token issued?
Yes, the service provider's WS-SecurityPolicy defines the Issuer element in the IssuedToken assertion.

Is there a standard mechanism to tell the intermediary which claims information the service provider requires in the issued token?

Yes, the service provider's WS-SecurityPolicy defines the Claims element in the IssuedToken assertion.

This logic doesn't have to be coded and managed statically within the intermediary in a non-standard compliant way. It's very flexible by just changing the policy information of the service provider.

In both intermediary solutions (with and without STS), if the intermediary has to communicate with a remote component (ID system or STS) it's recommended to cache issued security tokens for the duration of its lifetime to prevent requesting a new security token for each web service request retrieved by the intermediary.

How does the intermediary know how long should a token be cached?
How should the intermediary know if a security token has been issued for a specific service only?
This is fairly easy, the response of an STS usually returns a Lifetime and AppliesTo element. The cache can be built around the incoming security token id, the life time and appliesto information to build a flexible and token agnostic cache.

Last but not least, is there a web services stack which supports this functionality without having to write a single line of code?
Yes, it's Apache CXF. The intermediary use case is described in the above mentioned blog post. A system test and its configuration for the CXF STS is available too.


CXF is not the only web services stack supporting the intermediary case with an STS as the following article shows:



One question remains open, how can the service provider process claims information like roles, etc. which are encoded as an AttributeStatement in the SAML token? Do I have to implement and maintain this for Websphere, Weblogic, Tomcat, JBoss, etc.

This answer is no.
In one of my next posts I will explain how you reduce the complexity and increase interoperability of your web services deployment even you've got different application server stacks in house.



Categories: Oliver Wulff

SAML tokens and WS-Trust Security Token Service (STS)

Oliver Wulff - Mon, 02/27/2012 - 19:53
I was working actively in the Apache CXF community with respect to SAML tokens and WS-Trust SecurityTokenService (STS) since the donation of the STS to the community. I noticed in different projects that there is a lack of documentation about the different use cases for SAML tokens and WS-Trust STS.

I give a brief introduction into SAML and STS before bringing the two together.


SAML


SAML is an OASIS standard and provides a bunch of specifications. A SAML token is issued by an identity provider. A service provider relies on the identity provider to authenticate a principal. The SAML assertion is provided to the service provider thus he can make an access control decision. The most important problem SAML tried to solve is Web Single Sign On.

There is a clear layering between the SAML specifications thus you can re use them better in other contexts. Another context besides Web SSO is Web Services communication. I want to blog about SAML and Web Services communication. Therefore, we only look into the SAML Core specification as it  describes the syntax and semantics of SAML assertions. The SAML protocols are covered by SAML core too but there are not relevant for Web Services communication. This is also the case for the SAML bindings (how SAML messages are transmitted from one system entity to another) as well as for SAML profile. The latter describes use cases for Web application Single Sign On.

A SAML assertion (equal to SAML security token) contains different kind of statements: authentication-, attribute-, authorization decision statement. The "authorization decision statement" become deprecated in SAML 2.0 specification as it is covered in XACML and in claims based authorization based on standard SAML attribute statements. The former is quite complex whereas the latter provides already good options for fine grained authorization at less complexity. You can find more information about the latter here.


A SAML assertion contains a subject which identifies the principal. The subject can also contain additional information like key material and the subject confirmation method. One of the main topic in this blog are the different kind of subject confirmation methods and how they correlate to an STS.


As a side note, the subject confirmation method is not defined in the SAML core. Instead, the SAML profile specification defines the following three subject confirmation methods:
  • Holder of Key (HOK)
    The subject must contain key material thus the service provider is able to validate that the requestor is in the possession of the key(s)
  • Bearer
    The subject doesn't contain key material and it is up to the service provider to accept the assertion or not
  • Sender vouches (SV)
    The subject doesn't contain key material and it is up to the service provider to accept the assertion or not. The requestor and the identity provider are usually the same.

For more information about SAML I recommend wikipedia and the documentation at the OASIS committee.

Web Services and SAML

SAML in the context of Web Services is standardized in the SAML token profile here. It describes on the one hand how a SAML token is embedded in a SOAP message and on the other hand what kind of requirements must be met dependent on the SAML version and subject confirmation method.


I can highly recommend the following web services security usecases from OASIS as it describes very interesting use cases by combining transport level and message level security (ex. SAML HOK is very complex and has a performance impact as XML signature is required. This document describes how to use mutual ssl handshake for the proof-of-possession processing)

In 2011, a lot of new security features have been added to CXF. Check the following blog for more information.



WS-Trust STS


The WS-Trust standard introduces a runtime component called Security Token Service (STS). A service consumer requests a security token from the STS which is sent to the service provider. Either the service provider can validate the security token on its own or sends a request to the STS for validation. This pattern is based on an indirect trust relationship between the service provider and the STS. As long as the service consumer is in the possession of a security token issued by a trusted STS, the service provider accepts the token sent by the service consumer. This is the same pattern as for certificates and certificate authorities. This approach has significant advantages compared to a direct (brokered) trust established between a service provider and service consumer. The specification is an OASIS standard and can be downloaded here.

The STS can issue security tokens based on requirements provided by the service consumer and/or service provider. The requirements of the service provider are either expressed in a ws-policy document according to WS-SecurityPolicy or out-of-band agreement.


A key benefit of the STS is the reduced complexity for web service consumer. A web service consumer doesn't have to know about different kind of security tokens its service providers require. Instead, it sends a request to the STS containing the requirements of the client and the service provider and attaches the returned security token to the outgoing SOAP message to the service provider. One service provider could require a SAML 1.1 token, another a SAML 2.0 token and another a custom binary security token. The service consumer doesn't have to understand SAML 1.1, SAML 2.0 or the custom binary security token. All he has to do is grab the returned token from the STS and attach it to the message. Thus, you can reduce the complexity in your application and move it to a centralized component.


How does a web service consumer know whether it has to go to an STS to request a token? The policy of the service provider contains an IssuedToken assertion with some additional information like the address of the STS, token type, claims, etc.


Now, it's time to explain a few parameters of the request (RST) to the STS.


TokenType
specifies the type of security token requested (ex. SAML 1.1, 2.0, X.509, ...). URIs are defined for all standard security tokens.

KeyType
specifies the type of key desired in the security token. There are three URIs defined:
  • PublicKey
  • SymmetricKey
  • Bearer

Claims
specifies the required and optional claims in the security token. A claim can be the email address, role information, country, etc.


AppliesTo
specifies the scope for which the security token is required. This can be the URL of the service provider.


Lifetime
specifies the creation and expiration time of the security token. The STS is not obligated to honor this range.

These parameters can be retrieved from the WS-SecurityPolicy document also. In that case, they are added as child elements of the SecondaryParameters element in the RST.



SAML and STS 


How does a SAML token and the parameters sent to the STS match with each other. How does the STS know which subject confirmation method should be used? OK, let's start with the more obvious one.

1) TokenType
the token type is either SAML 1.1 or SAML 2.0. The STS creates the corresponding SAML assertion

2) AppliesTo
the appliesto element defines the scope and thus match to the SAML AudienceRestriction element in the SAML condition

3) Lifetime
the value of the lifetime or the lifetime choosen by the STS matchs to the SAML conditions NotBefore and NotAfter

4) Claims
the claim values maps to a SAML attribute statement. It's standardized here how claims are encoded as a SAML attribute statement. You can get more information about claims here.


How is the trust between the service provider and the STS established? This is fairly easy. The SAML assertion is signed by the STS. The signing certificate must be configured in the service provider to be trusted.


But how can the STS know whether the subject confirmation method should be HoK, SV or Bearer.
If the KeyType contains the value PublicKey or SymmetricKey, the subject confirmation method is Holder-Of-Key.
If the KeyType contains the value Bearer, the subject confirmation method is Bearer.

The benefit of HoK is that even somebody gets into the possession of a SAML token, he can't send request on behalf of the subject in the SAML token as it doesn't know the key (symmetric or private key). Therefore, a SAML token with Bearer subject confirmation method must be protected. In most cases, Bearer combined with HTTPS is sufficient to prevent that "a man in the middle" can get into the possession of the SAML token.

The subject confirmation methods Bearer and Holder-Of-Key are widely used for all STS use cases as well as for Web Single Sign On in WS-Federation Passive Requestor Profile and SAML Post Profile.


OK, what about sender-vouches? Even it is not clearly stated but it makes no sense to request a SAML token from an STS with sender-vouches subject confirmation method.


You might know this paper from IBM which describes how to get a SAML token from the STS with sender-vouches. Even it is from IBM, I don't change my opinion ;-)

Let's step back once and have a look what the differences are between a SAML token with subject confirmation method Bearer and Sender-Vouches. Finally, it is a string in the ConfirmationMethod element. Of course, an STS can put the string for Sender-Vouches into the SAML token - not a big deal.

The WS-Security SAML token profile defines the processing rules for HoK and Sender Vouches. In the case of Sender-Vouches it says that the attesting entity, (presumed to be) different from the subject, vouches for the verification of the subject. The receiver MUST have an existing trust relationship with the attesting entity. The attesting entity MUST protect the assertion in combination with the message content against modification by another party. The trust is established based on certificates where the attesting entity (service consumer) signs the SAML token and the SOAP body which is verified by the service provider. The receiver (service provider) must have imported the certificate of the service consumer.
A SV SAML token itself is not signed in constrast to Bearer and HoK because there is no third party like an STS. It doesn't make sense that an STS issues a SAML token which is not signed as you can't guarantee that an entity is adding additional statements.


Therefore, I'm saying that Sender-Vouches doesn't make sense in the context of STS.


Where is SAML Sender-Vouches used? I'll blog about this in a separate post.


Categories: Oliver Wulff

Configure Fediz IDP and ASP.NET using WIF

Oliver Wulff - Mon, 02/06/2012 - 13:26
Fediz provides different components to support single sign on and claims based authorization for web applications based on WS-Federation. As described here, the IDP/STS is the central component which authenticates users and issues security tokens (ex. SAML) which includes information about the authenticated identity, their keys and claims. The other component is deployed within the relying party, the web application. How you can enable WS-Federation for Tomcat is described here.
What about other technologies like Microsoft. WS-Federation is supported by Microsoft out-of-the-box by the Windows Identity Foundation (WIF). ASP.NET supports similar extension points like Tomcat to intercept and customize request processing and authentication. The counterpart of a Tomcat Valve is a .NET HttpModule.

WIF is a .NET assembly (DLL) which provides http modules, new config section and other stuff. Thus, you can enable WS-Federation for your ASP.NET based web application by configuration. There is a very good post about WIF and ASP.NET here. There is also a Visual Studio extension to generate a mock IDP based on ASP.NET and WIF but it doesn't have the functionality supported by the mock IDP as part of Fediz. You can create test users and assign any kind of claims to each users thus you can easily test your claims based ASP.NET web application. IMHO, there is another reason, isn't it cool to show how interoperable .NET and Java is !?

You can re-use the updated IDP provided here.

The following steps are required to use this mock IDP in your ASP.NET web application.

1. Deploy Windows Identity Foundation

You can download WIF here and install it. Finally, you only have to deploy the Microsot.IdentityModel.dll‎ to your bin directory of the web application.

 
2. Import the IDP/STS certificate in the Microsoft certificate store
You can get more information about the Microsoft certificate store here.
The relying party must establish a trust with the IDP/STS. This is achieved by trusting the certificate which was used to sign the SAML token. Windows and .NET have their own certificate store and doesn't understand a Java keystore (JKS). Therefore, we have to export the certificate in the JKS in a platform neutral format like PEM. You have to run the following command:

keytool -exportcert -alias mystskey -keystore stsstore.jks
-storepass stsspass -rfc -file sts.pem
Import the certificate file sts.pem into the store as described here.
Ensure that you import the certificate into the "Trusted People" store.


You are able to click on the certificate you imported before. The value of the field "Thumbprint" is required to establish the trust to the IDP within the relying party.






3. Configure WIF in web.config


Different sections of the web.config must be updated. First, you must configure the new config section for WIF:


   <configSections>
      <section name="microsoft.identityModel"
         type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
   </configSections>

Second, configure the http modules:

   <system.web>
      <httpModules>
         <add name="SessionAuthenticationModule"
            type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
         <add name="WSFederationAuthenticationModule"
            type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </httpModules>
Disable default authentication/authorization. Instead, the above http modules will handle authentication and authorization:
      <authentication mode="None" />
      <authorization>
         <deny users="?" />
      </authorization>

Configure WIF:


   <microsoft.identityModel>
      <service saveBootstrapTokens="true">
         <issuerNameRegistry      type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
            <trustedIssuers>
               <add thumbprint="977f0c1c0a2e9534d310a8e05380f5653524ca3f"
                  name="https://b0d0ma02.ch.zurich.com:16050/fedizidp/" />
            </trustedIssuers>
         </issuerNameRegistry>
         <certificateValidation
            certificateValidationMode="PeerTrust" revocationMode="Online"
            trustedStoreLocation="LocalMachine" />
         <audienceUris>
            <add value="https://teinf0095.emea.zurich.test/helloworld/" />
         </audienceUris>
         <federatedAuthentication>
            <wsFederation passiveRedirectEnabled="true"
               issuer="https://b0d0ma02.ch.zurich.com:16050/fedizidp/"
               realm="https://teinf0095.emea.zurich.test/helloworld/"
               requireHttps="true" />
            <cookieHandler requireSsl="false" name="FedAuth"
               hideFromScript="true" path="/helloworld" />
         </federatedAuthentication>
      </service>
   </microsoft.identityModel>


I'd like to highlight the following pieces in the section "microsoft.identityModel".

1) issuerNameRegistry
add the thumbprint to the issuerNameRegistry


2) audienceUris
add the valid uri's which must match with the audience restriction in the SAML token


3) federatedAuthentication
configure the URL of the IDP in the attribute "issuer" and the realm for the application. The realm matches with the audience restriction finally.




More information about WIF configuration can be found here.
That's it. You are ready for testing...


4. If it doesn't work...

1) A generic exception is returned by the .NET application without indicating the root cause.


There should be an error logged in the Microsoft Event Viewer (Administrative Tools) for the log type "Application".


2) SecurityTokenValidationException is returned by the application


exception details:
[SecurityTokenValidationException: The X.509 certificate E=sts@sts.com, CN=www.sts.com, OU=IT Department, O=Sample STS -- NOT FOR PRODUCTION, L=Baltimore, S=Maryland, C=US is not in the trusted people store.]


Certificate not imported into the Microsoft Certificate store (Trusted People store. See section 2.


3) SecurityTokenException


exception details:
[SecurityTokenException: ID4175: The issuer of the security token was not recognized by the IssuerNameRegistry. To accept security tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.]


Certificate not trusted. Ensure that the correct thumbprint is configured in web.config.
Categories: Oliver Wulff

Pages

Subscribe to Talend Community Coders aggregator - Oliver Wulff