Showing posts with label WSO2 API manager. Show all posts
Showing posts with label WSO2 API manager. Show all posts

Tuesday, July 16, 2013

OAuth 2.0 grant types with WSO2 API Manager - II - Implicit

This is the second of a series of posts related to OAuth-2.0 grant types in WSO2 API Manager (WSO2 Carbon platform). Therfore, I strongly suggest you to read and work on the examples described in the first post before proceeding with this.

In this post, we will go through Implicit grant type which is the recommended practice if your application (client) is a mobile application or a browser based app such as a JavaScript client.  The key difference of implicit grant when comparing to the Authorization Code is, the client receives access token as the result of the authorization request. In our previous post, which was about Authorization Code grant, client had to make separate requests for authorization and access token. Also note that, the implicit grant does not include client authentication because it does not make use of client secret.

Before attempting to work on the sample, let's have a look at the steps involved in implicit grant type.

1.   Application (client) does a token request from the authorization server by sending a HTTP GET request with the following query parameters.

response_type = token
client_id = VALUE_OF_CONSUMER_KEY
redirect_uri = REDIRECT_URL_OF_THE_APPLICATION
scope =  SCOPE_OF_THE_ACCESS_REQUEST

The first two are mandatory parameters where as the last two can be optional. 

2.  Upon receiving the request, the authorization server must return a 302 redirection back to the client with an Location header pointing to the URL of user consent page. (e.g:- Location: https://localhost:9443/carbon/oauth/oauth2_authn_ajaxprocessor.jsp)

3.  User (resource owner) confirms the authorization requested by client (application) by specifying his credentials.

4. Authorization server redirects user back to the application (to the callback url which has been specified at the first step) with the access token.


Let's explore more on the above steps, using our sample web application (acts as the client/application) and WSO2 API Manager (acts as the authorization server).


Step 1


Access the OAuth playground application as instructed in "Setting up client" section in the previous post. Once you click on "Import Photos" icon, you will be landed in a page where you will find a form with various options such as Authorization Grant Type, Client Id etc..

Step 2


Select Implicit as the Authorization Grant Type. 

Copy the consumer key value from the application you have subscribed in WSO2 API Manager (see above) and enter it in Client Id text box.

Specify any string value as scope. We do not really worry about scope attribute in this example. 

Enter callback URL which must be identical to the value you have specified at the time of creating the new application in WSO2 API Manager. 
e.g:- http://localhost:8090/playground2.0/oauth2client

Enter Authorize endpoint. This should be the endpoint of authorization server where it accepts the authorization requests. In WSO2 API Manager, there is an API to handle all authorization requests and it can be accessed through http://localhost:8280/authorize.

Once you completed adding all values in the form in the playground app, click on Authorize.

This will generate HTTP GET request similar to the following. You can see it contains all mandatory URL parameters which we have discussed in point 1 under the general introduction of "Implicit grant type".

GET /authorize?scope=api_scope&response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fplayground2.0%2Foauth2client&client_id=ePCzEHajPOZRKus4XS3pva_Ec5Ua HTTP/1.1

Host: 127.0.0.1:8281

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: en-us,es;q=0.7,en;q=0.3

Accept-Encoding: gzip, deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Connection: keep-alive

Referer: http://127.0.0.1:8090/playground2.0/oauth2.jsp?reset=true

Cookie: i18next=en-US; region1_configure_menu=none; region3_registry_menu=none; region4_monitor_menu=none; region5_tools_menu=none



Step 3


When you click on "authorize" with all required parameters, the application generates the above HTTP GET call and you will be redirected to the user consent screen as shown below. 








Click on Authorize. You will be provided with options to enter user name and password (username and password of the resource owner/end user).

Type admin/admin as user name and passeword respectively and click on login.

Step 4


You will receive the Access Token as shown below.












Now, we can use this access token to do the actual API call.

We will explore Client Credentials OAuth-2.0 grant type in our next post.

Monday, July 15, 2013

OAuth 2.0 grant types with WSO2 API Manager - I - Authorization Code

WSO2 API Manager is a complete open source solution to manage APIs. It provides authorization and authentication for APIs using OAuth 2.0 standard. According to the OAuth specification, the client needs to get authorization from the resource owner when requesting an access token. The authorization is expressed in the form of an authorization grant, which the client uses to request the access token. There are 4 grant types defined in the OAuth spec.

  • Authorization code
  • Implicit
  • Resource owner password credentials
  • Client credentials

Almost all scenarios explained in the online documentations written on WSO2 API Manager, make use of the Resource owner password credentials grant type. In there, we exchanges access token for user credentials and client_id and client_secret.

I'm going to explain the use of all 4 OAuth grant types using WSO2 API Manager through a serious of blog posts. In this post, I will explain how we can use Authorization Code grant type with WSO2 API Manager.

Pre-requisites:
==============
1. Download and install WSO2 API Manager-1.4.0
2. Install Apache Tomcat
















When calling an API hosted in WSO2 API Manager, we need to associate an OAuth access token as part of the requests HTTP header to authenticate the caller.

POST http://localhost:8280/myapi/1.0.0 HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "urn:echoInt"
Authorization: Bearer 21737b20a287fb4e207bf08bf3b17924
 

WSO2 API manager consists of multiple components to provide unique functionalities required to manage APIs hosted in it. Authorization server, which is one of such components, responsible for issuing tokens which are needed to authenticate API consumers.  Therefore, before making a API call, the application user should possess the relevant access token with him.

Obtaining access token can be done in multiple ways. In other words, the four of the above OAuth grant types can be used to obtain access token from the authorization server.
Let's see how we can obtain access tokens from each of the OAuth 2 grant types.


Setting up Client (Third party application)


As shown in the above picture, we will use a web application hosted in Apache Tomcat as the client.
Download playground2.0.war from here and copy it to TOMCAT_HOME/webapps directory. Make sure to update the following parameters in WEB-INF/web.xml



<servlet>
<servlet-name>oAuth2ClientServlet</servlet-name>
<servlet-class>com.wso2.identity.oauth.sample.OAuth2ClientServlet</servlet-class>
<init-param>
<description>serverUrl</description>
<param-name>serverUrl</param-name>
<param-value>https://localhost:9443/services/</param-value>

localhost is the server where we host WSO2 API Manager and 9443 is the default SSL port of it.
Also, make sure to update param-value of setup to AM as shown below.

<servlet>
<servlet-name>oAuth2AccessResourcePage</servlet-name>
<jsp-file>/oauth2-access-resource.jsp</jsp-file>
<init-param>
<description>setup</description>
<param-name>setup</param-name>
<param-value>AM</param-value>
</init-param>

Restart tomcat and access http://localhost:8080/playground2.0/ (assuming tomcat is running on HTTP port 8080). You will be directed to the landing page of our sample application. Click on Import Photos and you will be shown the following page.














We can use this application to request access tokens using the four OAuth2 grant types.

Create and subscribe to a new API in WSO2 API Manager


Before exploring OAuth grant types supported by WSO2 API Manager, we need to add an API using the API publisher web app in WSO2 API Manager, publish it to the API gateway component and finally subscribe to the API through API store web app. I'm not going to repeat those steps in this post since I have already explained them in one of my previous posts. You will also find the WSO2 API Manager official documentation useful. However, I will explain one modification which will be important to continue with our example.

In WSO2 API Manager, an application user subscribes to an API or multiple APIs through an application. The OAuth keys are generated per application. Once you have access token in a particular application, you can call any APIs associated with it using the same key.
When you add a new application, you will notice an option to include a Callback URL with the application (see below).


 








Callback URL is a redirection URI in the client application which is used by the authorization server to send the client's user-agent (usually web browser) back after granting access. In our example, we will use http://localhost:8090/playground2.0/oauth2client as the Callback URL.

Once you create the application, you can subscribe to one or more APIs using the new application. 













Make a note of access token, consumer key and consumer secret specific to your application. 

Authorization code grant type with API Manager

 

Authorization code grant type is the recommended approach if the client is a web server based application such as a servlet, JSP etc. The authorization code grant type can simply be explained using the following steps.

1.   Application (client) requests an authorization code from the authorization server by sending a HTTP GET request with the following query parameters.

response_type = code
client_id = VALUE_OF_CONSUMER_KEY
redirect_uri = REDIRECT_URL_OF_THE_APPLICATION
scope =  SCOPE_OF_THE_ACCESS_REQUEST

The first two are mandatory parameters where as the last two can be optional. 

2.  The authorization server must return a 302 redirection back to the client with an Location header pointing to the URL of user consent page. (e.g:- Location: https://localhost:9443/carbon/oauth/oauth2_authn_ajaxprocessor.jsp)

3.  User (resource owner) confirms the authorization requested by client (application) by specifying his credentials.

4. Authorization server responds back to the callback URL specified at the first step with an Authorization Code.

5.  Application makes a HTTP POST request to get access token with the following POST parameters

grant_type =  authorization_code
code = authorization_code_value_obtained_from_step_4
redirect_url = redirect_url_of_the_application
client_id = value_of_consumer_id
client_secret =  value_of_consumer_secret

6. Finally, the authorization server returns an access token optionally with a refresh token

Let's explore more on the above steps, using our sample web application (act as the client/application) and WSO2 API Manager (act as the authorization server).

Step 1


Access the OAuth playground application as instructed in "Setting up client" section. Once you click on "Import Photos" icon, you will be landed in a page where you will find a form with various options such as Authorization Grant Type, Client Id etc..

Step 2


Select Authorization Code as the Authorization Grant Type. 

Copy the consumer key value from the application you have subscribed in WSO2 API Manager (see above) and enter it in Client Id text box.

Specify any string value as scope. We do not really worry about scope attribute in this example. 

Enter callback URL which must be identical to the value you have specified at the time of creating the new application in WSO2 API Manager. 
e.g:- http://localhost:8090/playground2.0/oauth2client

Enter Authorize endpoint. This should be the endpoint of authorization server where it accepts the authorization requests. In WSO2 API Manager, there is an API to handle all authorization requests and it can be accessed through http://localhost:8280/authorize.

These APIs can be found in "Deployed APIs" page in API Manager management console (gateway) as shown below.








Once you completed adding all values in the form in the playground app, click on Authorize.

This will generate HTTP GET request similar to the following. You can see it contains all mandatory URL parameters which we have discussed in point 1 under "Authorization Code grant type".

GET /authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fplayground2.0%2Foauth2client&client_id=ePCzEHajPOZRKus4XS3pva_Ec5Ua%20&scope=my_scope HTTP/1.1

Connection: keep-alive

User-Agent: Jakarta Commons-HttpClient/3.1

Host: 127.0.0.1:8281


Step 3


When you click on "authorize" with all required parameters, the application generates the above HTTP GET call and you will be redirected to the user consent screen as shown below. 











Click on Authorize. You will be provided with options to enter user name and password (username and password of the resource owner/end user).

Type admin/admin as user name and passeword respectively and click on login.

Step 4


You will be directed to a new form with an Authorization Code. (see below)













Specify the same call back url which you have entered in step 2. (http://localhost:8090/playground2.0/oauth2client)

We are going to obtain an access token from the authorization server. Thus, we need to specify the endpoint URL of the API which returns access tokens. You can find it in the same way as we got the authorize endpoint from  "Deployed APIs" page in API Manager management console (gateway). It will be similar to http://localhost:8280/token

Specify client secret (consumer secret) value which can be found in the relevant application in the API store of  WSO2 API manager (see above).

 Click on Get Access Token. This will generate a HTTP POST request similar to the following.



POST /token HTTP/1.1

Content-Type: application/x-www-form-urlencoded

Cache-Control: no-cache

Pragma: no-cache

User-Agent: Java/1.6.0_29

Host: 127.0.0.1:8281

Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

Connection: keep-alive

Content-Length: 223



client_secret=fasxsVxJkTNzYtIAXxly8fR8s8ga+&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A8090%2Fplayground2.0%2Foauth2client&code=7dea8b1258febe471f2dad424dad6fd&client_id=ePCzEHajPOZRKus4XS3pva_Ec5Ua
 
Compare this with the mandatory parameters which we have explained under point number 5 in authorization code grant type.

Step 5


You will get an access token (typically a JSON response) which can be used to do the actual API call.  

We will discuss the usage of implicit OAuth grant type in the next post. Stay tuned!!!

Monday, July 2, 2012

Consuming a SOAP service using WSO2 API Manager

SO2 API Manager is the new kid in the block, the first fully open source API management platform which can be used to create, manage, consume and monitor APIs. WSO2 API manager is based on the award winning SOA middleware platform, WSO2 Carbon thus it inherits the features provided by the modular Carbon platform.
API authors and publishers can publish both REST and SOAP services to external consumers or partners through WSO2 API manager. In this post, we will look in to the steps of publishing and consuming a SOAP based web service using WSO2 API Manager.

pre-requisites:
Download and install alpha version of WSO2 API Manager from http://dist.wso2.org/products/api-manager/1.0.0-alpha/wso2am-1.0.0-ALPHA.zip. Similar to the other WSO2 Carbon products, you just need to have JDK-1.6.0 or later to run WSO2 API Manager. Then you can just extract the binary and start the server.

Step 1:

We will use a simple SOAP based web service hosted in WSO2 StratosLive Application Server. You can find the WSDL of the service at http://appserver.stratoslive.wso2.com/services/t/superqa.com/Axis2Service?wsdl

Step 2:

WSO2 API Manager consists of three different applications which serve for distinct user requirements. The API Gateway which is accessible through https://localhost:9443/carbon, is used as a gateway for API calls. The API Provider web app is used to publish, manage and monitor statistics of APIs. API provider can be accessed through https://localhost:9443/apiprovider. API Store application acts as the API consumer front end where users can subscribe for the published API. API Store is accessible through https://localhost:9443/apistore Ideally, three different user categories access these three applications. The API gateway is usually hosted and managed by API management provider. Therefore, we can assume that the default admin user of WSO2 API Manager as the API management provider thus he/she initiates creating rest of the user roles in the system. The API provider webapp is usually accessed by people who want to publish and manage new APIs. Therefore, we can think of another distinct role related to creating and publishing APIs. Finally, the API consumer user access API store webapp to subscribe for APIs.

Though we can use the default admin user to access all of the above applications, to be much realistic, lets start to create the roles and users associated to the API provider and API store applications.

  • Log in to API gateway app as admin user (user name=admin, password=admin).
  • Click on Configurein left menu and select Users and Roles
  • Click on Add New Role, enter "publisher" (or whatever you want) as the role name and click on next
  • Select the following permissions from the permission tree

Admin Permissions --> Configure --> Governance
Admin Permissions --> Login
Admin Permissions --> Manage --> API --> publish
Admin Permissions --> Manage --> API --> create
Admin Permissions --> Manage --> Resources --> Govern

























  • Click on Finish to complete the creation of new role
  • Now access the Users page and click on Add New User. (say 'charitha' as the user name of new user, password is 'charitha')
  • Assign the above role (publisher) to the new user
We have just created a new user who is granted permissions to access API provider webapp.

Step 3:


Access https://localhost:9443/apiprovider. The log in page of the API publisher application will be launched. Log in to the application using the credentials of the user which we have created in the previous step.
Click on Add menu item in the left navigation pane to add a new API.













Enter the following values for the mandatory fields in the above form.

Name: Axis2ServiceAPI
Context: /SOAPService
Version: 1.0.0
Endpoint URL: http://appserver.stratoslive.wso2.com/services/t/superqa.com/Axis2Service
Tier Availability: Bronze

Leaving the other default values as they are, click on Create to add the new API. The published API will be shown in the All APIs page and it will be in the CREATED state.


Step 4:



The APIs which are at the CREATED state cannot be consumed by any user. Therefore, we need to publish the API to API store. Click on the Axis2ServiceAPI-V1.0.0 in All APIs page which will direct you to the detailed information page of the selected API. Click on Lifecycles tab. Select the state as PUBLISHED. Select Push To Gateway option so that the API will be registered in the API gateway.













Clicking on Update will publish the API. If you see the log of API gateway, you will notice the following message. INFO - API Initializing API: charitha--Axis2ServiceAPI 


Step 5: 


Now, the API which we have created from the SOAP based web service is in PUBLISHED state so that a consumer can subscribe to the API and invoke it. API store can be used for the consumers to subscribe to APIs. Access https://localhost:9443/apistore/. The landing page of WSO2 API Store application will be shown. You will notice the API which just has been published in available in that page.
Click on Signup at the top right corner to register a new consumer user. Enter 'apiconsumer' as the username and 'apiconsumer123' as the password.
Log in to API store using the new consumer's credentials.


Step 6:


Now, we are inside the API Store web application. We should create an application to make API subscriptions and consumption. Click on My Applications tab.
Add a new application with the name, AxisApp as shown below.













We need to generate an OAuth key to consume any API. Click on the Axis2ServiceAPI - 1.0.0 in the API list or left pane of the API Store web application.  Select Axis2App from the Applications dropdown list at the right of the page and click on subscribe.









The "Subscription Successful" confirmation dialog will be popped up. Click on Go to My Subscriptions button to check our new API subscription.











Click on Generate in the above page to create a new API key. Once the key is generated, click on Show Key and copy the API key.

Step 5: Now, we have everything required to consume the API. API has been published to the store, subscribed to the API and possessed an API key. Lets invoke the API using any client. In this example, I will use soapUI, the world's best and most user-friendly web service invocation utility to invoke the API.

  • Create a new soapUI project or use an existing project. 
  • Add the following SOAP request to your soapUI project.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.carbon.wso2.org">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:echoString>
            <ser:s>charitha</ser:s>
      </ser:echoString>
   </soapenv:Body>
</soapenv:Envelope>

  • Add http://localhost:8280/SOAPService/1.0.0/ as a new endpoint url in soapUI request editor. (This url can be found under the overview tab of Axis2ServiceAPI - 1.0.0 in API store)
  • Add the following HTTP header 
Authorization: Bearer  <Your API key which has been generated when subscribing to the API >
  • Now, your soapUI request editor will be similar to the following.










  • Submit the request and check the response. Since we have subscribed under bronze tier, you will be allowed to send 1 request per minute