Entitlement Mediator with WSO2 Enterprise Service Bus (ESB)

The WSO2 Identity Server (IS) can function as a eXtensible Access Control Markup Language (XACML) Policy Decision Point (PDP) and the WSO2 Enterprise Service Bus (ESB) can function as a XACML Policy Enforcement Point (PEP). In this post I will explain the configurations available with WSO2 ESB to enforce XACML. The XAMCL standard refrains from specifying what method should be used to communicate from the PEP to the PDP. Many vendors have implemented their proprietary way of doing this. There is a standard around this called “Web Services Profile of XACML (WS-XACML) Version 1.0”. However there hasn’t been any development on this standard for quite a few years now and not much traction is being shown towards it due to its bias to SOAP and its  performance implications due to XML signatures. However the benefit of adopting a standard is the elimination of vendor locking. That is one day you may need move to a PDP from another vendor and still have the current PEP work with it; and if the communication was done based on standards and the new PDP also supports this standard you will easily be able to switch PDPs. Otherwise you may need to modify your existing PEP to adopt to the new PDP. The WSO2 Identity Server has its proprietary SOAP API, Thrift API and basic support of WS-XACML.

Adding Entitlement Mediator to a Sequence

Adding Entitlement Mediator to a Sequence

The PEP in WSO2 ESB is called ‘Entitlement Mediator’. You can engage this mediator within a sequence.

Entitlement Mediator Design View

Entitlement Mediator Design View

As you can see in the above picture, the Entitlement mediator has 4 child sequence references branching from it. ‘OnAccept’ is the sequence which is invoked when the Entitlement mediator returns a result of ‘Permit’. For any other results such as ‘Deny’, ‘Not Applicable’ or ‘Indeterminate’ from the PDP the mediator would invoke the ‘OnReject’ sequence. It is up to the administrator who configures the mediator to decide what to do with the two outcomes. E.g. If the result was ‘Permit’ the request could be directed to the back end service that was requested. If it was ‘Deny’ the request can be directed to a different endpoint or the WSO2 ESB may respond to the client with a message saying “Unauthorized!”. Following images show such a configuration.

OnAccept/OnReject Design View

OnAccept/OnReject Design View

OnAccept/OnReject Source View

OnAccept/OnReject Source View

The ‘Obligations’ and ‘Advice’ sequences are used to handle obligation and advice statements in the XACML response. If there are any obligation or advice statements in the XACML response, the current message context would be cloned and a new message context created and the obligation or advice statements respectively will be set to the SOAP body and the corresponding sequence will be invoked on it. These two sequences have been added as extension points where the user should design it as he want.The advice sequence will be invoked asynchronously and the Entitlement mediator will not wait for its response. The obligations sequence will be invoked synchronously and the Entitlement mediator will wait for its response. If the obligations sequence returns true the Entitlement mediator will proceed to the OnAccept sequence, but if the obligations sequence returns false the Entitlement mediator will proceed to the OnReject sequence. These sequences can be given in-line or by referring to sequences stored in the registry.

Entitlement Mediator Configuration

Entitlement Mediator Configuration

The above image shows the configuration section of the Entitlement mediator. The ‘Entitlement Service Client Type’ is to say which method of communication should be used between the PEP and the PDP. With SOAP there are two options that can be used depending on the method of authentication. You could either authenticate using the Authentication Admin service or using Basic Authentication headers. The Basic Authentication support is only available with WSO2 IS 4.0.0 onwards. With previous Identity Servers you could only use SOAP with Authentication AdminThrift uses its own authentication service over TCP. Thrift is available from IS 3.2.3 onwards. WS-XACML also uses Basic Authentication and is available from IS 4.0.0. ‘Entitlement Sever’ specifies the server URL of the WSO2 IS. This should take the value in the form of


if the Entitlement Service Client Type is set to SOAP or WS-XACML. If it is set to thrift then the Entitlement Server should have the value in the form of


The ‘User Name’ and ‘Password’ fields should take the credentials of a user who has privileges to invoke the Entitlement Service in WSO2 IS. ‘Thrift Host’ and ‘Thrift Port’ should be configured if the Entitlement Service Client Type is thrift. This is the host-port pair used to establish a thrift connection to the entitlement service. The default port on which the thrift service starts is 10500. The Entitlement mediator defines a set of hooks that can be optionally overridden which defines the subject-id, resource-id and action-id attribute IDs respectively of the Subject, Resource and Action categories of the XACML 3.0 request. This configuration is what is known as the ‘Entitlement Callback Handler’. In addition to the above 3 attribute IDs users can add any number of attribute IDs for any number of attribute categories as well. There are four out-of-the-box handlers which can be switched depending on the setup. These handlers exhibit certain behavior for some of the out-of-the-box scenarios that is available with WSO2 ESB. They are:

1. UT – Used if the proxy service is secured with Username Token security policy.
2. X509 – Used if the proxy service is secured with WS-Security policy which requires client certificate or secured with client authentication.
3. SAML – Used if the proxy service is secured with WS-Trust.
4. Kerberos Used if the proxy service is secured with Kerberos.

In addition to these, users can implement their own Entitlement Callback Handlers and plug them to the WSO2 ESB through the synapse configuration. This blog explains how to achieve this.

The properties available in the entitlement mediator can be found here. These properties define the default behavior of the Entitlement Mediator. Specific handlers override this behavior. The default UT handler, overrides the method how the subject-id attribute value is picked. It looks for the property by the name ‘username‘ in the Axis2 message context and sets its value as the XACML request subject-id value. This is because if UsernameToken security is enabled in ESB for a proxy service, once a user authenticates to this proxy service the username would be set to the Axis2 message context. Likewise the other handlers also look at various properties for values for the attributes and construct the XACML request. The following attribute IDs are used by the default handlers.

1. urn:oasis:names:tc:xacml:1.0:subject:subject-id of category urn:oasis:names:tc:xacml:1.0:subject-category:access-subject
2. urn:oasis:names:tc:xacml:1.0:action:action-id of category urn:oasis:names:tc:xacml:3.0:attribute-category:action
3. urn:oasis:names:tc:xacml:1.0:resource:resource-id of category urn:oasis:names:tc:xacml:3.0:attribute-category:resource
4. IssuerDN of category urn:oasis:names:tc:xacml:3.0:attribute-category:environment (used only by X509 handler)
5. SignatureAlgorithm of category urn:oasis:names:tc:xacml:3.0:attribute-category:environment (used only by X509 handler)


OAuth 2.0 with WSO2 Identity Server

The OAuth2.0 authorization delegation protocol has gained wide attraction among the API communities for its ease of implementation compared to OAuth1.0a which involves signatures. It provides specific authorization flows (grant types in OAuth2.0 terms) for web applications, mobile and native applications and browser based clients.

The WSO2 Identity Server has the capability to function as an OAuth2.0 Authorization server. It also supports OAuth1.0a but in this post I will only be talking about OAuth2.0 support.

One of the popular products from WSO2 is the WSO2 API Manager. This product uses the same OAuth2.0 feature from the WSO2 Identity Server (enabled by the componentized architecture of Carbon platform powered by OSGi).

The OAuth2.0 core specification defines 4 authorization grant types for 4 different use cases.

1. Authorization Code grant type

The OAuth1.0a core specification talks about only one type of authorization flow mainly, which is the 3-legged flow. Authorization Code grant type is pretty much the evolution of OAuth1.0a which eliminates the need for signatures and relies solely on transport layer security such as SSL. This is a 3-legged flow and is the recommended and dominantly used flow for web applications. This flow involves two separate requests. First to the authorization endpoint and secondly to the token endpoint. In the authorization endpoint the resource owner authenticates himself and authorizes the client for a specific scope for a specific time period. The authorization server would respond with an authorization code to a callback URL specified by the client. In the second step the client would authenticate himself to the token endpoint and exchange the authorization code to an access token.

2. Implicit grant type

This  grant type has only one request. That is the request to the authorization endpoint. The resource owner as in the previous grant type would authenticate himself at the authorization endpoint. However the second step in the previous request does not take place here, which is the authentication of the client. Therefore the clients that use this grant type are known as public or anonymous clients because they don’t authenticate themselves. This grant type is defined in case of clients that live on the browser such as JavaScript clients. Here the clients credentials are kept in the browser, therefore can be seen by the resource owner or anyone who has got access to the browser session. Hence the the clients credentials are not confidential anymore and authentication does not make sense. However the client_id must be sent which can be used for throttling and monitoring (SLA) purposes. This grant type should be used with care, at the discretion of the Authorization server.

3. Resource Owner Password Credentials grant type

This grant type again has only one request. But this one talks to the token endpoint. Here the resource owner would need to provide his credentials to the client and the client would send those credentials and his own credentials to the token endpoint and authenticate both parties with their respective credentials and get back the access token. This type of grant is useful in scenarios where there is no browsers involved such as mobile apps or Desktop apps. Again this type of grant should be allowed at the discretion of the authorization server, suitably for reasons such as if the client is not able to take advantage of the browser and the clients are generally trusted parties and are certified to be trusted by the resource owners.

4. Client Credentials grant type

This grant is the most simplest grant type available. In this case the client directly sends an access token request to the token endpoint with his credentials. There is no resource owner credentials involved here. I.e. the resource owners do not authenticate themselves or authorize clients. This grant type is generally used in cases where the resources are public or else if the client is accessing resources owned by himself. So why do we need an authentication scheme at all if the resources are public? Or why do we need OAuth2.0 instead of HTTP Basic Auth if the client is accessing his own resources? Well, the answer for the first question is to impose SLAs and do monitoring, metering and billing. The answer for the second question is that the OAuth2.0 model has some inherent advantages not found with HTTP Basic Auth. Mainly the client credentials are exchanged for an access token which is used thereafter and the client’s credentials can be safely discarded until the access token expires. Therefore the frequency at which the client’s credential is required is reduced. Also the scope and lifetime of access given to the access token can be controlled unlike giving away the credentials which means if the credentials are compromised the masqueraders who obtain the credentials have complete authority over the user’s account until such time the legitimate user comes to know this and changes his credentials at the authorization server. But even that might be too late if the masquerader has already changed the password of that account. In such a case the consequences can be devastating.

Once an access token is obtained regardless of the grant type used resource access is the same from the client’s perspective. The client would send a resource request with the access token to the resource server. The request path would ideally be intercepted by an entity which will validate the access token with the authorization server and decide whether to let the request to continue or not. How the access token validation happens between the authorization server and resource server is implementation specific of the authorization server which OAuth2.0 does not talk about. The WSO2 Identity Server currently exposes a SOAP endpoint for this purpose. The WSO2 API Manager provides a SOAP endpoint as well as a Thrift endpoint for this purpose.

The OAuth2.0 specification has provisions for extensions at many places. The authorization grants and access tokens types are two main examples. One of the earliest grant type additions to the OAuth2.0 specification is the “SAML 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants”. Although this is still at a draft stage we can see all the major players in the industry adopting this standard mostly with some level of customization. The WSO2 Identity Server also has support for this since its 4.1.0 release. I have talked about this support here. Another such extension grant type which is also at a draft stage is the “JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants”. There are two major access token types that have been widely adopted in the industry; the “Bearer Token” (an IETF standard) and the “OAuth 2.0 Message Authentication Code (MAC) Tokens” (an IETF draft). The WSO2 Identity Server currently supports only the Bearer Token profile. For someone who wants an alternative for accessing resources with signatures, there is a customization available here.

Another complement to the OAuth2.0 specification is the “OAuth 2.0 Token Revocation” draft. The WSO2 Identity Server supports this draft as well from its 4.1.0 release, and you can read about it here.

The OAuth Bible is a comprehensive compilation of OAuth1.0a and 2.0 terminology and all their major flows.

OAuth Token Revocation with WSO2 Identity Server

The OAuth Token Revocation functionality is available with WSO2 Identity Server 4.1.0. The OAuth Token Revocation implementation follows the specification here. There are two endpoints exposed from the token revocation feature.

1. REST endpoint at /oauth2endpoints/revoke

2. SOAP endpoint at /services/OAuthAdminService with operation revokeAuthzForAppsByResourceOwner

The REST endpoint is for OAuth2.0 clients who want to revoke any access granted to them by a resource owner. This could be at the discretion of the resource owner or otherwise. In other words this endpoint is meant for OAuth2.0 clients only, to authenticate themselves using client_id and client_secret and revoke the authorization granted to them. They may use the access token or refresh token for this purpose. Whichever token the client uses the result is the same; the client cannot access the user’s resource again until such time the user explicitly provides his grant by authorizing the client at the OAuth2.0 authorization server.

Following is an example of the request that needs to be sent to the revocation REST endpoint by OAuth2.0 client to revoke a token:

curl -X POST --basic -u "4xTplVAiQEwrBF6wYSW3cpyqYDoa:GREoG5f80kmg7uHNed2YwfJSxlQa" -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -k -d "token=d23e96c9bf2818fe5b4db0f8dbe829bb&token_type_hint=access_token" https://localhost:9443/oauth2endpoints/revoke

The token parameter used here can be an access token or refresh token. The token_type_hint parameter is optional. This parameter can take values access_token or refresh_token. The Identity Server will use this parameter to speed up the process of looking up the token by searching first in the set of tokens the client specifies (access_token or refresh_token). If the token is not to be found in the set the client claims it to be in, then the server will look for the token in the other set (refresh_token or access_token).

The SOAP endpoint on the other hand is for the resource owners to directly interact with the Authorization server and revoke authorization grants for applications they previously granted access to, without the OAuth2.0 application/client being an intermediary in the process. The use of this SOAP endpoint is demonstrated by the WSO2 Identity Server’s management console at Configure’ -> My Authorized Apps‘ for resource owners to login and revoke application authorization.

Following is a screen shot of the ‘My Authorized Apps’ page at an instance when the user ‘ResourceOwner’ has granted authorization to the application ‘Playground2.0’ created by user ‘AppDev’.

Application 'Playground2.0' created by user 'AppDev' granted authorization by user 'ResourceOwner'

Application ‘Playground2.0’ created by user ‘AppDev’ granted authorization by user ‘ResourceOwner’

The token revocation end-point also supports CORS (Cross-Origin Resource Sharing) specification and also JSONP (Remote JSON – JSONP).

CORS is supported through CORS-Filter which can be found here. The CORS Filter is designed to be plugged to a webapp using its deployment descriptor (web.xml). Since the OAuth2.0 endpoints in WSO2 Identity Server have been written as JAX-RS endpoints you can add the required CORS configurations to its deployment descriptor. You can find this webapp at <WSO2_IS_HOME>/repository/deployment/server/webapps/oauth2endpoints.war. Rather than editing the web.xml directly in the deployed directory, its easier to copy the oauth2endpoints.war file into another location, edit the web.xml and copy it back into the webapps folder and it will get hot deployed.

Example of a JSONP revocation request:

curl -X POST --basic -u "4xTplVAiQEwrBF6wYSW3cpyqYDoa:GREoG5f80kmg7uHNed2YwfJSxlQa" -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -k -d "token=d23e96c9bf2818fe5b4db0f8dbe829bb&token_type_hint=access_token&callback=package.myCallback" https://localhost:9443/oauth2endpoints/revoke

The callback parameter is optional.

SAML2 Bearer Assertion Profile for OAuth 2.0 with WSO2 Identity Server

One of the very first complements to the OAuth2.0 specification is the SAML2 Bearer Assertion Profile for OAuth2.0. This profile talks about two use cases for the SAML2.0 Assertion.

1. Using SAML2.0 assertions as authorization grants

2. Using SAML2.0 assertions for client authentication

Among the above two use cases the former is the one that is more commonly needed in enterprises. The WSO2 Identity Server has had support for this use case from its 4.1.0 release onwards. WSO2 Identity Server as an OAuth2.0 Authorization Server can accept SAML2 Assertions from OAuth2.0 clients as means of resource owner authentication and authorization and exchange it to OAuth2.0 access tokens in order to access protected resources on behalf of the resource owner.

Many existing enterprises that have implemented SOA rely on SAML. In the case of WSO2 Identity Server SAML is used in its Web SSO feature and STS feature. Such enterprises could face a situation where they now need to consume OAuth protected resources through APIs. OAuth and OAuth2.0 in particular are more recent specifications compared to SAML. An enterprise that has already got a working SAML2.0 based SSO infrastructure between itself and the Service Provider (SP) would prefer to use the existing trust relationship between the Identity Provider (IDP) and the Service Provider, even if the OAuth Authorization Server is entirely different from the IDP. Especially if there could be a cut down in the number of steps performed in the OAuth2.0 dance in obtaining an access token due to the fact that the clients have already authenticated themselves to the IDP and the resource owner has authenticated himself and authorized the client, enterprises are going to love it. The SAML2 Bearer Assertion Profile for OAuth2.0 is the answer to the question of how we leverage on the existing trust relationship between the SP and the IDP, by presenting the SAML2.0 token to the authorization server and exchanging it directly to an OAuth2.0 access token.

SAML2.0 Bearer Assertion Profile for OAuth2.0 Enterprise Use Case

SAML2.0 Bearer Assertion Profile for OAuth2.0 Enterprise Use Case

How to try the SAML2.0 Assertion grant type with WSO2 Identity Server

1. Create a SAML2 Assertion. You can use the command line client program from here. Extract the ZIP file, change directory into the extracted folder and execute the following command in the command line.

java -jar SAML2AssertionCreator.jar <saml2_assertion_issuer> <saml2_assertion_subject> <saml2_assertion_recipient> <saml2_asseertion_audience_restriction> <your_JKS_file> <your_JKS_password> <your_certificate_alias> <your_private_key_password>

The first argument to the program is the saml:Issuer value. The second argument is the saml:Subject -> saml:NameId value. The third argument is the value of saml:Subject -> saml:SubjectConfirmation -> saml:SubjectConfirmationData.Recipient. The fourth argument could actually take multiple values separated by commas which are added to the saml:AudienceRestriction element of the token. Each value is added as a saml:Audience element within saml:AudienceRestriction. The fifth argument points to the Java Key Store (JKS) file to be used for signing credentials. The sixth argument is the JKS password. The seventh argument is the alias of the public certificate to be used. The eighth argument is the password of the private key that is used for signing.

2. Download the WSO2 Identity Server from here. Start the WSO2 Identity Server and log in to the management console.

3. Register new Trusted Identity Provider. Go to Configure -> Trusted Identity Providers. Click on ‘Add New Trusted Identity Provider’. Enter a unique identifier for this Trusted Identity Provider across the tenant. Enter the Issuer value used to generate the SAML2 assertion into Trusted Identity Provider Issuer field. (The default Issuer value of the WSO2 Identity Server when acting as an SSO provider is ‘https://localhost:9443/samlsso‘. The default Identity Provider URL is also same as the Issuer value.) Upload the corresponding public certificate of the private key used to sign the SAML2 Assertion.

4. Create a new OAuth2.0 application under Main ->  Manage -> OAuth

5. Execute the following HTTP request using an HTTP client such as cURL or Advanced Rest Client in Google Chrome. I have listed the cURL command here.

curl -X POST -u "QlthIzYUOK5DS0BXW8Cy8uFJjKAa:XFfgPmTbMaQ5eScc0rSnAW9ZIgwa" -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" -d "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=PHNhbWxwOl...[omitted for brevity]...ZT4" https://localhost:9443/oauth2/token

The -u flag should specify the “<Client Id>:<Client Secret>” value. The assertion parameter should specify the base64url encoded SAML2.0 assertion. Copy and paste the value that was output by the command line client. Make sure you have carefully copied and pasted the exact same value produced by the client; no more no less, since that value can be quite large.

You would have now received the response from the token endpoint. The response would contain the access token, refresh token, expiry time and token type.

How to use Facebook as OAuth 2.0 Authorization Server with WSO2 API Manager

The WSO2 API Manager comes bundled with an API Gateway, OAuth 2.0 Authorization Server and API Store and API Publisher jaggery apps. To increase the first time users’ experience all these components come bundled in a single distribution that is able run on a single JVM. However production recommendation is to deploy the four (or atleast three with the jaggery apps together) in a distributed setup.

One can have a requirement to use the WSO2 API Gateway with an external OAuth 2.0 Authorization server. I.e. to decouple the resource server from the authorization server in OAuth 2.0 terms. The OAuth 2.0 specification is silent on this. It does not talk about the interaction between the Resource server and the Authorization server. WSO2 API Manager has its proprietary implementation for this. However this requirement can be achieved. This is possible to do by configuring a new API handler in place of the default APIAuthenticationHandler. Each API that is published to the WSO2 API Gateway consists of a set of 5 default API handlers that do authorization, throttling, usage monitoring, etc. However it is important to note that the throttling and monitoring are based on the authorization keys of the client. If the authorization is decoupled from the API Gateway we won’t be able to use the APIMgtUsageHandler, APIThrottleHandler, etc.

Let’s say we need to use Facebook as the OAuth 2.0 Authorization server with the WSO2 API Gateway. The following diagrams illustrate the current OAuth 2.0 access token validation model and the proposed new model.

Access Token Validation with WSO2 Authorization Server

Access Token Validation with WSO2 Authorization Server

Access Token Validation with Facebook Authorization Server

Access Token Validation with Facebook Authorization Server

MTOM + WS-Encryption + Rampart + WSO2 ESB

The behavior of Rampart when doing encryption of any attachments such MTOM is to Base64 encode the attachment, place it in the body and continue encrypting it as any other SOAP body payload. There are two simple solutions for this.
1. Use SSL
2. Write the WS-Security policy to exclude attachments from being encrypted.

For some people these two might be not be a solution. In this blog post I am trying to provide an alternative for them.

There is a configuration in Rampart to say, optimize a particular part in the soap message that is denoted using XPath. This optimization runs after any encryption. Using this you can direct Rampart to optimize the data that you just encrypted.

E.g. if you have a binary payload in your SOAP body and you want to encrypt it and send it as an attachment:
Your WS-SecurityPolicy would contain the following which says to encrypt the entire SOAP body.

<sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">

And your Rampart configuration would have the following which says to optimize the binary content found at the specified XPath location.

<rampart:namespace prefix="xenc" uri="http://www.w3.org/2001/04/xmlenc#"></rampart:namespace>

When working as above in the WSO2 ESB we encounter another problem. Imagine you’ve created a proxy service in the WSO2 ESB for a backend service which accepts an MTOM attachment. Now if the proxy service is not secured with any WS-Encryption then the the WSO2 ESB has no problems. You can try this out with the WSO2 ESB sample 51. The sample only talks about the unsecured proxy case. But you may go ahead and apply a out of the box security policy which involves only signatures and no encryption (Non-repudiation) and find that the sample is still working. But if you turn on a security policy which has encryption (e.g. Sign and encrypt – X509 Authentication) then the sample no longer works. The error at the backend service would look something like follows:

ContentID is null

This can be because of the reason explained earlier in the post, which is the client might be encoding it into the SOAP body payload and encrypting it. If you have followed the work around I have mentioned for that problem, then this is coming because of another problem. The way synapse handles MTOM is, when the SOAP message is received at the proxy service it transforms the SOAP message by adding back the binary attachment into the payload in the relevant part and saves some pointers as XPath expressins as to which were the attachment parts. What happens when leaving Synapse to the backend service is, the pointers are read back and the binary payload is again optimized as MTOM attachments. In our case the MTOM optimization is not handled by Synapse but instead by Rampart. This does not make sure that the message leaving Synapse is optimized. Actually Synapse does not even know that this message consisted an attachment because the Rampart module in the proxy service of the WSO2 ESB has taken care of the security processing and returned the SOAP body to a state where it does not contain any security related tags. That is the part denoted by the XPath


is no more there in the SOAP body. Therefore unless we use another WS-SecurityPolicy for the endpoint of the WSO2 ESB and explicitly do the optimization the message leaving Synapse is not going to be optimized. However there seems to be an issue in that approach as well. It seems to be impossible with Rampart to have a WS-SecurityPolicy with only OptimizedParts configuration specified and no real security applied. Rampart ignores processing the complete policy if it does not find some minimum required configurations in the policy. Therefore this approach is also not going to work.

So the only workaround I was able to do was to write a class mediator for WSO2 ESB and explicitly MTOM optimize the binary payload.

How to try this

1. Setup sample 51 of WSO2 ESB.

2. The source code of the class mediator which does the explicit MTOM optimization can be found here. Add this to


3. The synapse configuration for the proxy service can be found here.
4. The custom security policy to be applied to the proxy service can be found here. Upload this security policy to the registry and apply it to the proxy service by selecting the “Policy From Registry” option.
5. The source code of the client program can be found here. Make sure the lib folder inside the project is added to the Java class path. Also you need to configure the client.properties file according to your environment.

This was tested with WSO2 ESB 4.5.1.

Signature verification with WSO2 API Manager

Digital signatures provide means of authentication, integrity and non-repudiation. OAuth 1.0a had digital signatures in it which are used during the “OAuth Dance” (an unofficial term used by Google developers to describe the set of steps performed in order to do the full OAuth authentication and authorization process to receive and access token) and as well as when going to access the protected resources with an access token. In OAuth 2.0 digital signatures were removed from the “OAuth Dance” citing the difficulty for the clients to do signing and primarily relied on transport layer security such as SSL over HTTP. OAuth 2.0 supports an extensible list of token profiles. The widely used profile is the bearer token profile. This profile does not involve any signatures with it. Another popular profile is the MAC token profile. There may be certain situations where users might prefer to have some kind of signatures and verification of them to have non-repudiation during the access token validation process. The MAC token profile seems the ideal candidate for this. The difference between OAuth 1.0a and OAuth 2.0 with MAC access tokens is that the MAC access token profile does not have to have signatures during the “OAuth Dance”.

The WSO2 API Manager currently only supports OAuth 2.0 bearer token profile out of the box.  It still does not support MAC token profile. But in case if you would want to have non-repudiation during the access of protected resources we have a work around that we can do. This work around is possible by adding a new ‘API Handler’ before the default ‘Authentication Hander’. It mimics the MAC token profile but is not an exact implementation of the profile. As of now this could be useful because we need not change any WSO2 API Manager code and you get signatures and signature verification during resource access.

This new handler is designed to work together with the default APIAuthenticationHandler which expects a bearer token by default. How it works is by sitting in front of the default handler, verifying the signatures in the request and converting the Authorization header to what the default handler expects and hands over the request to the default handler. This signature is calculated by signing the normalized request string by the consumer secret (which is where this implementation defers from the MAC token profile because we are not signing with a MAC key that was received in the token response step). This ensures that even if the bearer token is compromised, an illegitimate user is denied access to APIs, because he/she is unable to calculate the correct signature without knowing the shared consumer secret.

Signature verification can be implemented as an API handler similar to the ‘APIAuthenticationHandler’ or ‘APIUsageHandler’. After the introduction of this feature, the access token that was provided earlier can now function as the Mac Identifier. The consumer secret is used as the Mac key, which is a shared secret between the consumer and the provider used to sign the normalized request string. Timestamps and nonce are added to prevent replay attacks.

Engaging the Handler to an API

Follow the steps below to engage the handler to an API.


For demonstration purposes, we use selected WSO2 API Manager sample and .jar files in the steps below. Similar steps apply to other user-specific samples as well.

1. A compiled binary of a sample signature verification handler can be found here. The source code for this project can be found here.
Open the .jar file and search for the ‘verifier.properties’ file. It contains 4 properties as follows:

allowed.time.delay – The allowed time difference between the timestamp sent and the current time.

timediff.map.max.size – Maximum size of the map that should be maintained to keep timestamps, in order to prevent replay attacks.

nonce.map.max.size – Maximum size of the map that should be maintained to keep nonce values, in order to prevent replay attacks.

hash.algorithm – Hashing algorithm supported by SunJCE. For example, “HMacSHA1”, “HMacSHA256”, etc.

2. Copy the provided jar file to <AM_HOME>/repository/components/dropins folder where <AM_HOME> is the root of the WSO2 API Manager distribution. This is the location where any custom libraries are added.

3. Start WSO2 API Manager and log in to its Management Console.

4. Build the API Manager ‘YouTube’ sample using the instructions given up to section ‘Invoking the API’. Instructions can be found here

5. You can engage the developed handler to the API through the Management Console. Log in to the console and select ‘Main’ > ‘Service Bus’ > ‘Source View’.

6. In the ESB configuration that opens, as the first handler in the YouTube API, add the following line above ‘APIAuthenticationHandler’.

<handler class="org.wso2.carbon.apimgt.gateway.verifier.SignatureVerificationHandler"/>
SignatureVerificationHandler engaged to Youtube API

SignatureVerificationHandler engaged to Youtube API

The class ‘org.wso2.carbon.apimgt.gateway.verifier.SignatureVerificationHandler’ is the handler that we have implemented by extending the ‘org.apache.synapse.rest.AbstractHandler’ class and packed into the .jar file.

Invoking the API

Now that you have engaged the developed handler to the API, let’s see how to invoke this API using a REST client such as cURL. Note that none of the steps until invoking the API in the ‘YouTube’ sample have changed due to engaging the handler. The change only occurs in the way the API is invoked. Note the following differences in the new REST calls.

Previous cURL request (As seen in API Manager 1.3.0 documentation):

curl -H "Authorization :Bearer 8f74ac7a87caee6967b75dcda51b8edc" http://localhost:8280/youtube/1.0.0/most_viewed

Previous authorization header:

Authorization :Bearer 8f74ac7a87caee6967b75dcda51b8edc

New cURL request:

curl -H "Authorization :MAC id=\"8f74ac7a87caee6967b75dcda51b8edc\",ts=\"1347023000\",nonce=\"a1b2c3d4e5\",mac=\"5X/zg3RnRSMP1JkaMJCaqWOk/srpw4ybGwIbPRVNUYA=\""http://localhost:8280/youtube6/6.0.0/most_viewed

New authorization header:

Authorization :MAC id=\"8f74ac7a87caee6967b75dcda51b8edc\",ts=\"1347023000\",nonce=\"a1b2c3d4e5\",mac=\"5X/zg3RnRSMP1JkaMJCaqWOk/srpw4ybGwIbPRVNUYA=\"

The difference of the REST calls lies only in the Authorization header as follows:

The access token in the previous request has now become the ‘id’. ‘ts’ is the timestamp. It can be any positive integer value the client sends (ideally the number of seconds elapsed from 1/1/1970 0:0:0). However, a timestamp verification is done from the second request onwards from a particular ‘id’. The ‘nonce’ also is a string that is chosen by the client. It needs to be unique to the combination of timestamp and Mac identifier.

Considerations When Executing the new cURL Request

When invoking a cURL request with the new authentication header, every request from the same Mac identifier (which is the access token in the earlier method) should have a different timestamp value whose difference in value from the previous request is greater than the actual time elapsed between the previous request and this one. The Mac value is taken by creating the ‘Normalized Request’ string as shown in the ‘HMacGenerator’ console output, and hashing it using the ‘SunJCE’ library with the algorithm specified in ‘verifier.properties’ file. Then, we use the ‘ConsumerSecret’ as key and transcode it using Base64. Request String is equal to the full URL that comes in, minus the transport protocol (http,https) and the hostname:port pair. In other words, it is the string from the context onwards. URL encoding is done only for the query parameter values using the “UTF-8” encoding scheme. A Java client to generate HMac signature can be found in here. All required parameters including the algorithm to be used can be given as console inputs. Any algorithm that is supported by the SunJCE cryptographic provider such as “HMacSHA1”, “HMacSHA256”, etc. can be given. Before you run the command, ensure that the jar file in the ‘lib’ folder of the ‘HMacGenerator.jar’ is added to the Java classpath.