Showing posts with label SAML. Show all posts
Showing posts with label SAML. Show all posts

SAML 2.0 Bearer Assertion Profile for OAuth 2.0

SAML 2.0 Bearer Assertion Profile which is built on top of OAuth 2.0 Assertion Profile defines the use of a SAML 2.0 Bearer Assertion as a means for requesting an OAuth 2.0 access token as well as for use as a means of client authentication.

The OAuth 2.0 Assertion Profile is an abstract extension to OAuth 2.0 that provides a general framework for the use of Assertions as client credentials and/or authorization grants with OAuth 2.0.

This specification profiles the OAuth 2.0 Assertion Profile...

1.  To define an extension grant type that uses a SAML 2.0 Bearer Assertion to request an OAuth 2.0 access token when a client wishes to utilize an existing trust relationship, expressed through the semantics of (and digital signature calculated over) the SAML Assertion, without a direct user approval step at the authorization server.

2.  To define how a SAML Assertion can be used as a client authentication mechanism. The use of an Assertion for client authentication is orthogonal to and separable from using an Assertion as an authorization grant. They can be used either in combination or separately.

This specification further defies the format and processing rules for the SAML Assertion are intentionally similar, though not identical, to those in the Web Browser SSO Profile defined in SAML Profiles.

Now let's have a look at an end to end scenario which explains how to use SAML 2.0 Bearer Assertion as an grant type.


1. User been redirected to the SAML2 IdP and user authenticates to the SAML2 IdP.

2. SAML2 IdP issues a SAML2 Token with following characteristics and Client Web App verifies the SAML2 token and authenticates the user.
  • The Assertion's Issuer element will contain a unique identifier for the entity that issued the Assertion - which is the SAML2 IdP in our case.
  • The Assertion will contain Conditions element with an AudienceRestriction element with an Audience element containing a URI reference that identifies the Authorization Server.
  •  The Assertion will contain Conditions element with an AudienceRestriction element with an Audience element containing a URI reference that identifies the Client Web App, which is the SAML2 Service Provider and Client Web App must verify element.
  •  The Assertion MUST contain a Subject element. The subject MAY identify the resource owner for whom the access token is being requested. When using an Assertion as an authorization grant, the Subject SHOULD identify an authorized accessor for whom the access token is being requested (typically the resource owner, or an authorized delegate).
  • The Assertion MUST have an expiry that limits the time window during which it can be used. The expiry can be expressed either as the NotOnOrAfter attribute of the Conditions element or as the NotOnOrAfter attribute of a suitable SubjectConfirmationData element.
  •  The element must contain at least on element that allows the authorization serve to confirm it as a Bearer Assertion.  Such a element MUST have a Method attribute with a value of "urn:oasis:names:tc:SAML:2.0:cm:bearer".
  • The SubjectConfirmation element MUST contain a SubjectConfirmationData element, unless the Assertion has a suitable NotOnOrAfter attribute on the Conditions element, in which case the SubjectConfirmationData element MAY be omitted. When present, the SubjectConfirmationData element MUST have a Recipient attribute with a value indicating the token endpoint URL of the authorization server (or an acceptable alias). The  SubjectConfirmationData element MUST have a NotOnOrAfter attribute that limits the window during which the Assertion can be confirmed.  The SubjectConfirmationData element MAY also contain an Address attribute limiting the client address from which the Assertion can be delivered.  Verification of the Address is at the discretion of the authorization server.
  • The Assertion MUST have an expiry that limits the time window during which it can be used. The expiry can be expressed either as the NotOnOrAfter attribute of the Conditions element or as the NotOnOrAfter attribute of a suitable SubjectConfirmationData element.
  •  If the Assertion issuer authenticated the subject, the Assertion SHOULD contain a single  AuthnStatement representing that authentication event.
  •  If the Assertion was issued with the intention that the presenter act autonomously on behalf of the subject, an AuthnStatement SHOULD NOT be included.  The presenter SHOULD be identified in the NameID or similar element, the element, or by other available means.
  • Other statements, in particular elements, MAY be included in the Assertion.
3. Now Client Web App wants to access a RESTful service which secured with OAuth 2.0 and it has to get an access token on behalf the logged in user first. Now using the SAML2 grant type, Client Web App Requests an access token from the OAuth 2.0 Authorization Server.

     POST /token.oauth2 HTTP/1.1
     Host: as.example.com
     Content-Type: application/x-www-form-urlencoded

     grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Asaml2-bearer&
     assertion=PHNhbWxwOl...[omitted for brevity]...ZT4


4. Authorization Server validates the SAML token assertion and issues an access token back. Authorization Server does the SAML token verification as mentioned below.
  • The Assertion will contain Conditions element with an AudienceRestriction element with an Audience element containing a URI reference that identifies the Authorization Server and Authorization Server must verify the element.
  •  The SubjectConfirmation element MUST contain a element, unless the Assertion has a suitable NotOnOrAfter attribute on the Conditions element, in which case the SubjectConfirmationData element MAY be omitted. When present, the  SubjectConfirmationData element MUST have a Recipient attribute with a value indicating the token endpoint URL of the authorization server (or an acceptable alias).  The authorization server MUST verify that the value of the Recipient attribute matches the token endpoint URL (or an acceptable alias) to which the Assertion was delivered.  The SubjectConfirmationData element MUST have a NotOnOrAfter attribute that limits the window during which the Assertion can be confirmed.  The SubjectConfirmationData element MAY also contain an Address attribute limiting the client address from which the Assertion can be delivered.  Verification of the Address is at the discretion of the authorization server.
  • The authorization server MUST verify that the NotOnOrAfter instant has not passed, subject to allowable clock skew between systems. An invalid NotOnOrAfter instant on the Conditions element invalidates the entire Assertion.  An invalid NotOnOrAfter instant on a SubjectConfirmationData element only invalidates the individual SubjectConfirmation .  
  • The authorization server MAY reject Assertions with a NotOnOrAfter instant that is unreasonably far in the future.  The authorization server MAY ensure that Bearer Assertions are not replayed, by maintaining the set of used ID values for the length of time for which the Assertion would be considered valid based on the applicable NotOnOrAfter instant.
 5. Now Client Web App can use the access token to access the secured service.

The depth of SAML [SAML Summary]

1. History

Security Assertion Markup Language (SAML) is an XML standard for exchanging authentication and authorization data between entities which is a product of the OASIS Security Services Technical Committee.

- SAML 1.0 was adopted as an OASIS standard in Nov 2002
- SAML 1.1 was ratified as an OASIS standard in Sept 2003
- SAML 2.0 became an OASIS standard in Mar 2005

Liberty Alliance donated its Identity Federation Framework (ID-FF) specification to OASIS, which became the basis of the SAML 2.0 specification. Thus SAML 2.0 represents the convergence of SAML 1.1, Liberty ID-FF 1.2, and Shibboleth 1.3.

2. SAML base standards

SAML is built upon the following technology standards.

- Extensible Markup Language (XML)
- XML Schema
- XML Signature
- XML Encryption (SAML 2.0 only)
- Hypertext Transfer Protocol (HTTP)
- SOAP

3. SAML Components

Assertions: Authentication, Attribute and Authorization information
Protocol: Request and Response elements for packaging assertions
Bindings: How SAML Protocols map onto standard messaging or communication protocols
Profiles: How SAML protocols, bindings and assertions combine to support a defined use case

4. Assertions and Protocols for SAML v2.0

The Security Assertion Markup Language (SAML) defines the syntax and processing semantics of assertions made about a subject by a system entity. In the course of making, or relying upon such assertions, SAML system entities may use other protocols to communicate either regarding an assertion itself, or the subject of an assertion. This specification defines both the structure of SAML assertions, and
an associated set of protocols, in addition to the processing rules involved in managing a SAML system. This specification is considered as the SAML Core specification and these constructs are typically embedded in other structures for transport, such as HTTP form POSTs and XML-encoded SOAP messages.

5. Bindings for SAML v2.0

Bindings for SAML specifies SAML protocol bindings for the use of SAML assertions and request-response messages in communications protocols and frameworks.

Mappings of SAML request-response message exchanges onto standard messaging or communication protocols are called SAML protocol bindings (or just bindings). An instance of mapping SAML requestresponse message exchanges into a specific communication protocol <FOO> is termed a binding for SAML or a SAML <FOO> binding. For example, a SAML SOAP binding describes how SAML request and response message exchanges are mapped into SOAP message exchanges.

The intent of this specification is to specify a selected set of bindings in sufficient detail to ensure that independently implemented SAML-conforming software can interoperate when using standard messaging or communication protocols.

Following bindings are covered under this specification.

- SAML SOAP Binding
- Reverse SOAP (PAOS) Binding
- HTTP Redirect Binding
- HTTP POST Binding
- HTTP Artifact Binding
- SAML URI Binding

6. Profiles for SAML v2.0

Profiles for SAML specifies profiles that define the use of SAML assertions and request-response messages in communications protocols and frameworks, as well as profiles that define SAML attribute value syntax and naming conventions.

One type of SAML profile outlines a set of rules describing how to embed SAML assertions into and extract them from a framework or protocol. Such a profile describes how SAML assertions are embedded in or combined with other objects (for example, files of various types, or protocol data units of communication protocols) by an originating party, communicated from the originating party to a receiving party, and subsequently processed at the destination. A particular set of rules for embedding SAML assertions into and extracting them from a specific class of <FOO> objects is termed a <FOO> profile of SAML.

For example, a SOAP profile of SAML describes how SAML assertions can be added to SOAP messages, how SOAP headers are affected by SAML assertions, and how SAML-related error states should be reflected in SOAP messages.

Another type of SAML profile defines a set of constraints on the use of a general SAML protocol or assertion capability for a particular environment or context of use. Profiles of this nature may constrain optionality, require the use of specific SAML functionality (for example, attributes, conditions, or bindings), and in other respects define the processing rules to be followed by profile actors.

Following profiles are covered under this specification.

- SSO Profiles of SAML [Web Browser SSO Profile,Enhanced Client or Proxy (ECP) Profile, Identity Provider Discovery Profile, Single Logout Profile, Name Identifier Management Profile]
- Artifact Resolution Profile
- Assertion Query/Request Profile
- Name Identifier Mapping Profile
- SAML Attribute Profiles

7. Metadata for SAML v2.0

SAML profiles require agreements between system entities regarding identifiers, binding support and endpoints, certificates and keys, and so forth. A metadata specification is useful for describing this information in a standardized way. This specification defines an extensible metadata format for SAML system entities, organized by roles that reflect SAML profiles. Such roles include that of SSO Identity Provider, SSO Service Provider, Affiliation, Attribute Authority, Attribute Requester, and Policy Decision Point.

This specification further defines profiles for the dynamic exchange of metadata among system entities, which may be useful in some deployments.

8. Conformance Requirements for SAML v2.0

This normative specification describes features that are mandatory and optional for implementations claiming conformance to SAML V2.0 and also specifies the entire set of documents comprising SAML V2.0.

9. Web Services Security: SAML Token Profile 1.1

This specification describes how to use SAML V1.1 and V2.0 assertions with the Web Services Security SOAP Message Security V1.1 specification.

10. SAML 2.0 profile of XACML

The OASIS eXtensible Access Control Markup Language [XACML] is a powerful, standard
language that specifies schemas for authorization policies and for authorization decision requests and responses.

This profile defines how to use SAML 2.0 to protect, transport, and request XACML schema instances and other information needed by an XACML implementation.

11. Security and Privacy Considerations for SAML

This non-normative document describes and analyzes the security and privacy properties of SAML defined in the core SAML specification and the SAML bindings and profiles specifications.

12. SAML V2.0 Kerberos Attribute Profile

This specification defines an attribute profile for the Kerberos protocol. The SAML V2.0 Kerberos Attribute Profile describes a SAML attribute profile for requesting and expressing Kerberos protocol messages. In this version of the specification, this is constrained to the Kerberos KRB-CRED message type. The mechanisms that are used to generate the Kerberos message are outside the scope of this document and are described by IETF RFC 4120: 'The Kerberos Network Authentication Service (V5)'.

13. SAML V2.0 Change Notify Protocol

The SAML V2.0 Change Notify Protocol describes request and response messages for informing SAML endpoints about available changes to subjects and attributes associated with subjects.

SAML Assertions and XML Signature

SAML assertions and SAML protocol request and response messages may be signed, with the following benefits:

1. An assertion signed by the SAML authority supports:
– Assertion integrity.
– Authentication of the SAML authority to a SAML relying party.
– If the signature is based on the SAML authority’s public-private key pair, then it also provides for non-repudiation of origin.

2. A SAML protocol request or response message signed by the message originator supports:
– Message integrity.
– Authentication of message origin to a destination.
– If the signature is based on the originator's public-private key pair, then it also provides for non-repudiation of origin.

The [1] talks about only signing the Assertion - and [2] talks about signing the request as well as the response message which also carries the Assertion.

A digital signature is not always required in SAML. For example, it may not be required in the following situations:

- In some circumstances signatures may be “inherited," such as when an unsigned assertion gains protection from a signature on the containing protocol response message. "Inherited" signatures should be used with care when the contained object (such as the assertion) is intended to have non-transitory lifetime. The reason is that the entire context must be retained to allow validation, exposing the XML content and adding potentially unnecessary overhead.

- The SAML relying party or SAML requester may have obtained an assertion or protocol message from the SAML authority or SAML responder directly (with no intermediaries) through a secured channel, with the SAML authority or SAML responder having authenticated to the relying party or SAML responder by some means other than a digital signature.

It is recommended that, in all other contexts, digital signatures be used for assertions and request and response messages. Specifically:

- A SAML assertion obtained by a SAML relying party from an entity other than the SAML authority SHOULD be signed by the SAML authority.
- A SAML protocol message arriving at a destination from an entity other than the originating site SHOULD be signed by the origin site.

XML Signatures are intended to be the primary SAML signature mechanism.

Unless a profile specifies an alternative signature mechanism, enveloped XML Digital Signatures MUST be used if signing. This is bit different from the signature pattern recommended in WS-Security specification.

WS-Security specification says..

"Because of the mutability of some SOAP headers, producers SHOULD NOT use the Enveloped Signature Transform defined in XML Signature. Instead, messages SHOULD explicitly include the elements to be signed. Similarly, producers SHOULD NOT use the Enveloping Signature defined in XML Signature".

Although this contrasts with what is recommended in SAML specification - WS-Security doesn't have nothing to with SAML. SAML becomes a token type for WS-Security and SAML specification has the full control to define it's own recommendation for signing.

Why SAML specification recommends enveloped signature?

With enveloped signature, the signature element will be inside the element been signed it self - which is the Assertion element.

Enveloped signature is useful when we have a signed XML document that we wish to insert into other XML documents. Which is the case with SAML Assertion. There you get the SAML Assertion from the issuer and include it in to a request to the service provider.

SAML implementations also SHOULD use Exclusive Canonicalization [Excl-C14N], with or without comments, both in the element of , and as a algorithm. Use of Exclusive Canonicalization ensures that signatures created over SAML messages embedded in an XML context can be verified independent of that context.

Exclusive Canonicalization tries to figure out what namespaces you are actually using and just copies those. Specifically, it copies the ones that are "visibly used", which means the ones that are a part of the XML syntax. However, it does not look into attribute values or element content, so the namespace declarations required to process these are not copied. For example if you had an attribute like xx:foo="yy:bar" it would copy the declaration for xx, but not yy. It also does not copy the xml: attributes that are declared outside the scope of the signature.

Exclusive Canonicalization allows you to create a list of the namespaces that must be declared, so that it will pick up the declarations for the ones that are not visibly used.

Exclusive Canonicalization is useful when you have a signed XML document that you wish to insert into other XML documents - as in a signed SAML assertion which might be inserted as a XML Token in the security header of various SOAP messages. The Issuer who signs the assertion will be aware of the namespaces being used and able to construct the list. The use of Exclusive Canonicalization will insure the signature verifies correctly every time.

In contrast, the Inclusive Canonicalization copies all the declarations that are currently in force, even if they are defined outside of the scope of the signature. It also copies any xml: attributes that are in force, such as xml:lang or xml:base. This guarantees that all the declarations you might make use of will be unambigiously specified. The problem with this is that if the signed XML is moved into another XML document which has other declarations, the Inclusive Canonicalization will copy them and the signature will be invalid. This can even happen if you simply add an attribute in a different namespace to the surrounding context.

References :
1. http://www.oasis-open.org/committees/download.php/3406/oasis-sstc-saml-core-1.1.pdf
2. http://lists.oasis-open.org/archives/wss/200311/msg00058.html

Subject Confirmation support with Apache Rampart : Holder-of-Key

The Subject Confirmation is the process of establishing the correspondence between the subject and claims of SAML statements (in SAML assertions) and SOAP message content by verifying the confirmation evidence provided by an attesting entity.

SAML 1.1 Token Profile talks about three subject confirmation methods.

1. Holder-of-key Subject Confirmation Method
2. Bearer-key Subject Confirmation Method
2. Sender-vouches Subject Confirmation Method

With Holder-of-key Subject Confirmation Method, the attesting entity demonstrates that it is authorized to act as the subject of a holder-of-key confirmed SAML statement by demonstrating knowledge of any key identified in a holder-of-key SubjectConfirmation element associated with the statement by the assertion containing the statement. Statements attested for by the holder-of-key method MUST be associated, within their containing assertion, with one or more holder-of-key SubjectConfirmation elements.

Let's see how this works..

First the client application needs to request a token from the Security Token Service or the STS. This request is known as RST [wst:RequestSecurityToken] and goes inside the SOAP Body. Following is a sample RST.

   http://schemas.xmlsoap.org/ws/2005/02/trust/Issue
   
   
    
     http://localhost:8280/services/echo
    
   
   
    2011-11-15T10:29:17.487Z
    2011-11-15T10:34:17.487Z
   
   http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1
   
   http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey
   
   256
   
    nVY8/so9I3uvI3OSXDcyb+9kxWxMFNiwzT7qcsr5Hpw=
    
   
   http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1
   
  
Let's have a look at some of the key elements in the RST.

1. AppliesTo

This is the end point where the client going to use this token against.

2. KeyType : http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey

Use Symmetric key when generating the key for the SubjectConfirmation.

3. KeySize

Use this key size when generating the key for the SubjectConfirmation.

4. Entropy/BinarySecret

WS-Trust allows the requestor to provide input to the key material via a wst:Entropy element in the request. The requestor might do this to satisfy itself as to the degree of entropy (cryptographic randomness if you will) of at least some of the material used to generate the actual key which is used for SubjectConfirmation.

5. Entropy/ComputedKeyAlgorithm : http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1

The key derivation algorithm to use if using a symmetric key for P, where P is computed using client, server, or combined entropy.

With http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1 the key is computed using P_SHA1 from the TLS specification to generate a bit stream using entropy from both sides. The exact form is:
key = P_SHA1 (EntREQ, EntRES)
It is RECOMMENDED that EntREQ be a string of length at least 128 bits.

Now let's see how this request been processed at the STS end.

Based on the Key Type in the request - STS will decide whether to use Holder-of-key or not. For following key types, holder-of-key subject confirmation method will be used.

1. http://docs.oasis-open.org/ws-sx/ws- trust/200512/PublicKey
2. http://docs.oasis-open.org/ws-sx/ws- trust/200512/SymmetricKey

If it is SymmetricKey - then STS will generate a key - encrypt the key using the public certificate corresponding to the end point attached to the AppliesTo element in the RST and add that to the SubjectConfirmation element in the response.

Key generation is once again bit tricky.

If client provides an entropy and the key computation algorithm is http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1 then, the key is generated as a function of the client entropy and the STS entropy.

If client provides an entropy but the key computation algorithm is NOT http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1 then, the key is same as the client entropy.

If neither of above happens, then the server generates an ephemeral key.

Whatever the way the key is generated, it will be encrypted with the certificate corresponding to the AppliesTo end point and will be added in to the SubjectConfirmation element in the response.

        urn:oasis:names:tc:SAML:1.0:cm:holder-of-key
        
        
         
          
          
           
            Ye9D13/K1GFRvJjgw1kSr5/rYxE=
           
          
          
           a/kALeV0b0Y3oNcE7fdepUuF0sbQUGs012r87BMBUx/FL8Hc+kw/BGrRThEGGmDmVgJ8GdJw34nQM6IjulNV+hj/MmtXLSKZnjm7uLPPT3kgT0udzc8OuSgLVRO8ghcDK12/IiPAtzWZIfPS/ZT8kx4DSYWnvcNa4mTMM4wBhjt29bvAJcKZD0CqvJOLIFWc2FrQqNkym4UIF+GEcsN3rQcYDzoyiCm2L4RAm3u+1d+9zsQIEo8DtqDDboA0MAVbbM6xU3JbF35dLifmpwlsuiJC0y8VlAoN6wnNIJ/tpr4C4FhvdKnShAOeDf3D2JkZxr4ZNZZL91aHFaPpFbC9YQ==
           
          
         
        
       
As per the above code, what you see inside CipherValue element is the encrypted key. And it is encrypted from a certificate which is having the thumbprint reference Ye9D13/K1GFRvJjgw1kSr5/rYxE=. In other words, only the service which owns the certificate having the thumbprint reference Ye9D13/K1GFRvJjgw1kSr5/rYxE= would be able to decrypt the key - which is in fact the service end point attached to the AppliesTo element. BTW... can anybody in the middle fool the service endpoint just by replacing the SubjectConfirmation element..? This is prevented by STS signing the SubjectConfirmation element along with Assertion parent element with it's private key. So - the SAML token is protected for integrity.

Okay... now the token is at the client end... In which ways the client application going to use this token.

One way is to use it as a SupportingToken and the other way is to use it as a ProtectionToken.

When we use SAML token as a ProtectionToken, client application can use it to encrypt/sign the messages going from the client to the service end point. Then the question is which key would the client use to sign and encrypt - it's the same key added to the SubjectConfirmation by the STS - but it's encrypted with the public key of the service end point - so, client won't be able to decrypt it and get access to the hidden key.

There is another way, STS passes the generated key to the client. Let's look at the following element also included in the response passed from the STS to the client - this is out side the Assertion element.
<wst:Entropy>
    <wst:BinarySecret
     Type="http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce">3nBXagllniQA8UEAs5uRVJFrKb9dPZITK76Xk/XCO5o=
    </wst:BinarySecret>
   </wst:Entropy>
Here in the Entropy/BinarySecret STS passed the entropy created to generate the key. The key is generated as a function of the client entropy and the STS entropy - client already knows the client entropy and can find the STS entropy inside Entropy/BinarySecret in the response - so, client can derive the key from those.

Following would be the WS-Security Policy at the service end, which expects SAML token as a ProtectionToken.
<wsp:Policy wsu:Id="SgnOnlyAnonymous"
 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
 xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
 <wsp:ExactlyOne>
  <wsp:All>
   <sp:SymmetricBinding>
    <wsp:Policy>
     <sp:ProtectionToken>
      <wsp:Policy>
       <sp:IssuedToken
        sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
        <Issuer xmlns="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
         <Address xmlns="http://www.w3.org/2005/08/addressing">http://localhost:8080/axis2/services/STS
         </Address>
        </Issuer>
        <sp:RequestSecurityTokenTemplate>
         <t:TokenType xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1
         </t:TokenType>
         <t:KeyType xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey
         </t:KeyType>
         <t:KeySize xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">256</t:KeySize>
        </sp:RequestSecurityTokenTemplate>
        <wsp:Policy>
         <sp:RequireInternalReference />
        </wsp:Policy>
       </sp:IssuedToken>
      </wsp:Policy>
     </sp:ProtectionToken>
     <sp:AlgorithmSuite>
      <wsp:Policy>
       <sp:Basic128 />
      </wsp:Policy>
     </sp:AlgorithmSuite>
     <sp:Layout>
      <wsp:Policy>
       <sp:Lax />
      </wsp:Policy>
     </sp:Layout>
     <sp:IncludeTimestamp />
     <sp:OnlySignEntireHeadersAndBody />
    </wsp:Policy>
   </sp:SymmetricBinding>
   <sp:SignedParts>
    <sp:Header Name="To" Namespace="http://www.w3.org/2005/08/addressing" />
    <sp:Body />
   </sp:SignedParts>
   <sp:Wss11>
    <wsp:Policy>
     <sp:MustSupportRefKeyIdentifier />
     <sp:MustSupportRefIssuerSerial />
     <sp:MustSupportRefThumbprint />
     <sp:MustSupportRefEncryptedKey />
     <sp:RequireSignatureConfirmation />
    </wsp:Policy>
   </sp:Wss11>
   <sp:Trust10>
    <wsp:Policy>
     <sp:MustSupportIssuedTokens />
     <sp:RequireClientEntropy />
     <sp:RequireServerEntropy />
    </wsp:Policy>
   </sp:Trust10>
  </wsp:All>
 </wsp:ExactlyOne>
</wsp:Policy>
When we use the SAML token as a SupportingToken, we basically doing nothing from it that sending it as it is to the service end in the SOAP Security Header. SubjectConfirmation goes useless here - but service end can verify whether the token been issued by a trusted STS, by verifying the signature.

Following is the WS-Security Policy at the service end - which expects SAML token as a SupportingToken.
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
 wsu:Id="SigEncr">
 <wsp:ExactlyOne>
  <wsp:All>
   <sp:SupportingTokens
    xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
    <wsp:Policy>
     <sp:IssuedToken
      sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
      <Issuer xmlns="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
       <Address xmlns="http://www.w3.org/2005/08/addressing">
        https://localhost:9443/services/wso2carbon-sts
       </Address>
      </Issuer>
      <sp:RequestSecurityTokenTemplate
       xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
       <t:TokenType>
        urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
       <t:KeyType>
        http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey
       </t:KeyType>
       <t:KeySize>256</t:KeySize>
       <t:Claims Dialect="http://wso2.org/claims"
        xmlns:ic="http://schemas.xmlsoap.org/ws/2005/05/identity">
        <ic:ClaimType Uri="http://wso2.org/claims/givenname" />
       </t:Claims>
      </sp:RequestSecurityTokenTemplate>
      <wsp:Policy>
       <sp:RequireInternalReference />
      </wsp:Policy>
     </sp:IssuedToken>
    </wsp:Policy>
   </sp:SupportingTokens>
  </wsp:All>
 </wsp:ExactlyOne>
</wsp:Policy>

Extracting SAML assertions from a proxy service and adding them back to the service behind

This blog post explains how to do the intial setup with WSO2 ESB and the Identity Server to develop claim aware web services - please go through it first.

There - we get the SAML Assertion to the proxy service.

Here what we are going to do is - to extract SAML Assertions from the Security header of the incoming message and add those as a custom header to the message going to the actual service.

First, please download the org.wso2.carbon.identity.samples.saml.mediator-2.0.0.SNAPSHOT.jar from here.

Stop - the ESB if it's running already.

Copy the above jar to [ESB_HOME]\webapps\ROOT\WEB-INF\plugins\console.

Open [ESB_HOME]\webapps\ROOT\WEB-INF\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info and add the following entry to the end [one line].

org.wso2.carbon.identity.samples.saml.mediator,2.0.0.SNAPSHOT,file:plugins/org.wso2.carbon.identity.samples.saml.mediator-2.0.0.SNAPSHOT.jar,10,true

Start the ESB with following.

\> wso2server.bat -cleanCache

Now, you need to add the above mediator to the in sequence of your proxy service as a Class mediator.

Following is the synapase configuration for the in/out sequences of the proxy service.

<syn:proxy name="test" transports="https http" startOnLoad="true" trace="disable">
  <syn:target>
    <syn:inSequence>
      <syn:class name="org.wso2.carbon.identity.samples.saml.mediator.SAMLAttrMediator"/>
      <syn:header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" name="wsse:Security" action="remove"/>
      <syn:log level="full"/>
      <syn:send/>
    </syn:inSequence>
    <syn:outSequence>
      <syn:send/>
    </syn:outSequence>
  </syn:target>
</syn:proxy>
You can clearly see Class/Header/Log & Send mediators are in the in-sequence and Send mediator in the out-sequence.

Now - the question is how do we capture the SAML attributes from the actual service.

You can call the following method from any service method to get the attributes in a HashMap.

getAttributes(MessageContext.getCurrentMessageContext());

Following is the code for getAttributes() method.

private static final String USER_ATTRIBUTES_ELEMENT = "UserAttributes";
private static final String USER_ATTRIBUTES_NS = "http://attributes.saml.axis2.org";
private static final String ATTRIBUTE = "Attribute";
private static final String ATTRIBUTE_NS = "AttributeNamespace";
private static final String ATTRIBUTE_VALUE = "AttributeValue";
public final static String SAML10_NS = "urn:oasis:names:tc:SAML:1.0:assertion";
public final static String SAML11_NS = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
public final static String SAML20_NS = "urn:oasis:names:tc:SAML:2.0:assertion";

public Map getAttributes(MessageContext messageContext) {
OMElement header = null;
OMElement userAttr = null;
Iterator iterator = null;
String samlNameSpace = null;

header = messageContext.getEnvelope().getHeader();
userAttr = header.getFirstChildWithName(new QName(USER_ATTRIBUTES_NS,
USER_ATTRIBUTES_ELEMENT));
iterator = userAttr.getChildrenWithName(new QName(SAML10_NS, ATTRIBUTE));

if (iterator.hasNext()) {
samlNameSpace = SAML10_NS;
} else {
iterator = userAttr.getChildrenWithName(new QName(SAML11_NS, ATTRIBUTE));
if (iterator.hasNext()) {
samlNameSpace = SAML11_NS;
} else {
iterator = userAttr.getChildrenWithName(new QName(SAML20_NS, ATTRIBUTE));
if (iterator.hasNext()) {
samlNameSpace = SAML20_NS;
}
}
}

if (samlNameSpace == null) {
// Unsupported SAML token type;
return null;
}

Map attributes;
attributes = new HashMap();

while (iterator.hasNext()) {
OMElement attr = iterator.next();
OMElement attrValElement = null;
String attributeName = null;
String attributeValue = null;
attributeName = attr.getAttributeValue(new QName(ATTRIBUTE_NS));
attrValElement = attr.getFirstChildWithName(new QName(samlNameSpace, ATTRIBUTE_VALUE));
attributeValue = attrValElement.getText();
attributes.put(attributeName, attributeValue);
}

return attributes;
}
Also make sure you import following packages as well.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.MessageContext;