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.

Advertisements

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

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.

Note:

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.