Quantcast
Channel: Sanjeewa Malalgoda's Blog
Viewing all 220 articles
Browse latest View live

Add documents with different media types and search content of them / Search documents by passing part of key word - WSO2 API Manager

$
0
0
API Manager default document search implementation will work only with registry stored document content files with the media types defined in registry.xml under tag as below.

Text : text/plain
PDF : application/pdf
MS word : application/msword
MS Powerpoint : application/vnd.ms-powerpoint
MS Excel : application/vnd.ms-excel
XML : application/xml


Therefore documents added through the url will not work as that type doesn't have stored document content in registry. As a workaround we can add .jag/.html document files to the registry as API documents, then we need to write custom indexers for those media types and update the registry.xml file with those indexers.

For htmls you may use already available xml indexer as its almost same to xml.

<indexer class="org.wso2.carbon.apimgt.impl.indexing.indexer.XMLIndexer" mediaTypeRegEx="application/xml" profiles ="default,api-store,api-publisher"/>



Also when you search part of the string contained in text you may use following search query for that.  Having * symbol at start and end will help you to search documents which contains that part in any word.

doc:*part_of_text*

How to address API Store console API invocation issue if browser completely disabled CORS and prevent calls to other domains - WSO2 API Manager

$
0
0
In internet explorer we can  set Access data sources across domains as follows. This option specifies whether components that connect to data sources should be allowed to connect to a different server to obtain data. This applies only to data binding, such as active data objects. The settings are as follows:
Enable allows database access to any source, even other domains.
Prompt prompts users before allowing database access to any source in other domains.
Disable allows database access only to the same domain as the page.

Due to some organization policies we do not allow any cross origin requests from the web browser. Which means we have to prevent browsers from doing CORS. API Store console function performs a cross origin request, if you don't allow the web browser to perform CORS the function simply cannot work.
 
The sole reason for the CORS specification to exist and be supported by standard web browsers is to allow cross origin requests safely.

So if you are allowing only store domain to access from browser then only solution is send gateway requests to same domain and map them to gateway.
In that case we may need reverse proxy or load balance to front API store node. Then mapping should be done as follows.

>apim.store.wso2.com/store
This should go to API store store_host_name:9443/store

>apim.store.wso2.com/gateway
This should route to API gateway api_gateway_host_name:8243/api_context/version/


Then in store node we need to configure gateway URL to point reverse proxy/load balancer as gateway URL. So from browser side it do not need to send requests to multiple domains. It sends all requests to same domain and sub context(/gateway, /store) will help to resolve exact host.

Why API cal fails when HTTP transport is only enabled in api gateway but curl works - WSO2 API Manager

$
0
0
Sometimes you may noticed when http transport is only enabled in api gateway API cal fails from  API console but curl works. Reason for this issue is you are on http browser session and call https URL.

You are seeing this issue because you are trying to access HTTP back end from HTTPS browser sessions. Browser will not allow to call HTTP back end from HTTPS session. This pattern called mixed content[1] and most of the browsers will not allow it as mixed content weaken HTTPS. If you need to access HTTP back end from user them what you need to do is go to HTTP store URL with 9763(http://127.0.0.1:9763/store/) and invoke API. So i believe we need to fix this from browser side or client side.

Also usually in production we do not recommend to use http transport for API calls. And according to oauth specifications it was recommend to use oauth tokens over HTTPS.


[1]https://developers.google.com/web/fundamentals/security/prevent-mixed-content/what-is-mixed-content?hl=en

WSO2 Deployment architecture for small organizations who wish to expose their services to outside world.

$
0
0

In this post i will explain how small and medium size organizations can expose their APIs to outside world using WSO2 products. Also we will explain how we can expose services combining existing services and newly implemented services. For this solution i will use API Manager, Identity Server, Enterprise Service Bus and Data Services Server.

Please see below deployment diagram.

rfi.jpg


  • The main product used for integration purposes would be the Enterprise Service Bus. This would be responsible to carry out the system to system integration scenarios across the various systems. All heavy mediation logics should happen at this layer. Also service chaining, implement API facade pattern, message aggregation should happen at this layer. To achieve high availability we may need ESB cluster for this. External and internal service integration will happen at this layer and expose composite service to API Management layer.

  • The Identity Server product is needed in the solution if advanced security requirements such as user authentication and permission validation etc. Also we may consider having Identity server as key Manager for API Manager. Then all token validation/ introspection happens with Identity Server nodes.

  • WSO2 API Manager will be used to expose all services to outside as APIs and apply quality of services for API. All authentication, throttling and QoS application happens at this layer. To have clear separation between components we would like to suggest separate clusters for gateway workers, store/publisher, gateway managers and key managers. Then based on the system load we can scale each component without scaling all components and can achieve high availability as well.

  • WSO2 Data Services Server augments service-oriented architecture development efforts by providing an easy-to-use platform for integrating data stores, creating composite data views, and hosting data services. This product will be used to expose organization data to external world as services. 

How to validate JSON request pay load before passing to back end - WSO2 API Manager

$
0
0
Sometimes users need to validate request data before process them and forward to mediation flow. In this article i will discuss about how we can validate input request json message.

First you need to identify message you need to validate. In this sample i will use following JSON message.
'{"greet": {"name": "sanjeewa"}}'


Before any processing is happen i need to verify at least we have one single element with name because without name back end cannot process request further.
So in request name is mandatory parameter. Now lets write XSD to validate input request. With XSDs you cannot validate exact JSON messages but as you know inside synapse run time
all messages will converted to xml message and flow continue. So we can log incoming message and how it looks like during the mediation flow. Then we can write XSD validation logic as follows.
Please refer this article on how we can validate messages using xsd(http://soatutorials.blogspot.com/2014/08/validating-xml-messages-against-more.html).
To validate my request i created following XSD.

<xs:schemaxmlns:xs="http://www.w3.org/2001/XMLSchema"

xmlns:ns1="http://org.apache.axis2/xsd"xmlns:ns="http://www.wso2.org/types"
attributeFormDefault="qualified"elementFormDefault="unqualified">
<xs:elementname="jsonObject">
 <xs:complexType>
  <xs:sequence>
   <xs:elementname="greet">
    <xs:complexType>
      <xs:sequence>
       <xs:elementminOccurs="1"name="name">
        <xs:simpleType>
         <xs:restrictionbase="xs:string">
             <xs:minLengthvalue="1" />
         </xs:restriction>
        </xs:simpleType>
       </xs:element>
     </xs:sequence>
    </xs:complexType>
   </xs:element>
  </xs:sequence>
 </xs:complexType>
</xs:element>
</xs:schema>


Then we need to upload this XSD to registry. So we can use this during the message mediation flow. So i will go to registry browser and add it to this(/_system/config/schema.xsd) location.

Now i need to implement validate sequence which actually validate message. For that i created following sequence and engage it to mediation flow of API.
Please refer below sequence. There i created error payload and send error message if validation failed. Else message will continue to mediation flow. As you can see here i have referred previously created XSD to validate message.

<sequencexmlns="http://ws.apache.org/ns/synapse"name="WSO2AM--Ext--In--validateJSON"

<validate>
    <schemakey="conf:/schema.xsd"/>
         <on-fail>
     <payloadFactorymedia-type="xml">
        <format>
            <am:faultxmlns:am="http://wso2.org/apimanager">
                <am:code>555</am:code>
                <am:type>Status report</am:type>
                <am:message>Runtime Error</am:message>
                <am:description>Request format is incorrect</am:description>
            </am:fault>
        </format>
    </payloadFactory>
    <propertyname="RESPONSE"value="true"/>
    <headername="To"action="remove"/>
    <propertyname="HTTP_SC"value="555"scope="axis2"/>
    <propertyname="NO_ENTITY_BODY"scope="axis2"action="remove"/>
    <propertyname="ContentType"scope="axis2"action="remove"/>
    <propertyname="Authorization"scope="transport"action="remove"/>
    <propertyname="Access-Control-Allow-Origin"value="*"scope="transport"/>
    <propertyname="Host"scope="transport"action="remove"/>
    <propertyname="Accept"scope="transport"action="remove"/>
    <propertyname="X-JWT-Assertion"scope="transport"action="remove"/>
    <propertyname="messageType"value="application/json"scope="axis2"/>
    <send/>
    </on-fail>
</validate>
</sequence>



Then i will add this sequence to mediation flow while creating API as follows.


Then i will save and publish this API and invoke it as follows.
First i will invoke API with wrong JSON payload and i will type name as name1(which is wrong according to XSD). Then users should get error message as we defined in validate sequence.

curl-v-k-XPOST--header'Content-Type: application/json'
 --header'Accept: application/xml'--header'Authorization: Bearer a5e48a2ed76ba7437b452d7687a20a6b'
 -d'{"greet": {"name1": "sanjeewa"}}''http://172.17.0.1:8280/validateAPI/1.0.0/'
*  Trying172.17.0.1...
*Connectedto172.17.0.1 (172.17.0.1) port8280 (#0)
>POST/validateAPI/1.0.0/HTTP/1.1
>Host:172.17.0.1:8280
>User-Agent:curl/7.43.0
>Content-Type:application/json
>Accept:application/xml
>Authorization:Bearera5e48a2ed76ba7437b452d7687a20a6b
>Content-Length:32
>
*uploadcompletelysentoff:32outof32bytes
<HTTP/1.1555
<Access-Control-Allow-Origin:*
<Content-Type:application/json; charset=UTF-8
<Date:Mon, 08Aug201609:16:46GMT
<Transfer-Encoding:chunked
<
*Connection#0 to host 172.17.0.1 left intact
{"fault":{"code":555,"type":"Status report","message":"Runtime Error","description":"Request format is incorrect"}}


So you can see error message as as we defined in validate sequence.
Now i will send correct JSON message as follows.

curl-v-k-XPOST--header'Content-Type: application/json'
--header'Accept: application/xml'
--header'Authorization: Bearer a5e48a2ed76ba7437b452d7687a20a6b'
-d'{"greet": {"name": "sanjeewa"}}'
'http://172.17.0.1:8280/validateAPI/1.0.0/'

*  Trying172.17.0.1...
*Connectedto172.17.0.1 (172.17.0.1) port8280 (#0)
>POST/validateAPI/1.0.0/HTTP/1.1
>Host:172.17.0.1:8280
>User-Agent:curl/7.43.0
>Content-Type:application/json
>Accept:application/xml
>Authorization:Bearera5e48a2ed76ba7437b452d7687a20a6b
>Content-Length:31
>
*uploadcompletelysentoff:31outof31bytes
<HTTP/1.1200Success
<Access-Control-Allow-Origin:*
<Access-Control-Allow-Methods:DELETE,POST,PATCH,PUT,GET
<Access-Control-Allow-Headers:authorization,Access-Control-Allow-Origin,Content-Type
<Content-Type:text/html
<Location:https://www.test.com/
<Date:Mon, 08Aug201609:17:23GMT
<Transfer-Encoding:chunked
<
<html>
<head><title>302Found</title></head>
<bodybgcolor="white">
<center><h1>302Found</h1></center>
<hr><center>nginx/1.9.15</center>
</body>
</html>


As you can see here it will validate properly and send to nginx back end and it returns 302 as response.



How to hide carbon.super tenant domain from tenant API store.

$
0
0
If you need to hide carbon.super tenant domain please follow the instructions below.
in template.jag(/store/site/themes/fancy/templates/api/tenant-stores-listing/template.jag) paste following before this line(just after for loop). Change highlighted in blue color. 
<%for(var i=0;i< tenantDomains.length;i++){

if(tenantDomains[i] !="carbon.super"){
varsite=require("/site/conf/site.json");
%>
<ahref="<%= encode.forHtmlAttribute(encode.forUri(jagg.getSiteContext() + 
"
?tenant="+tenantDomains[i])) %>"title="<%=tenantDomains[i]%>"><liclass="thumbnail span3 tenent-thumb">
<center><imgsrc="<%=jagg.getAbsoluteUrl(jagg.getThemeFile("images/tenant-store.png"))%>"alt="">
<h3><%=tenantDomains[i]%></h3>
<span>VisitStore</span>
</center></a></li><%}}%>


Then it will filter out carbon.super from main store view. You can do this change using sub theme and override default page. To do that please follow this article about API Manager sub themes.


How to manage 2 different environments(production and sandbox) and let only paying users to access production environment- WSO2 API Manager

$
0
0
Requirement.
Let users to come to store and consume APIs.
Then users should be able to try APIs and test them.
Once they ready to pay for them and use it for production scenarios then they should go through approval process. If they validated then only will be able to use production APIs.

Solution
Let users to self signup or create by admin via management console.
Then let them to subscribe APIs and use them. At the time they subscribe we will show message saying “You can invoke API 10 times per minute with sandbox token and if you need to use it for production then need to go through approval process and generate production keys”.
Sandbox key generation do not need to have workflow and anyone should be able to create sandbox keys and invoke APIs with them.
Then users should use sandbox keys until they need to use them for real production usage.

We need to implement new handler to throttle sandbox API requests. Inside the handler you can check user is invoking production or sandbox with following code block.

if (APIConstants.API_KEY_TYPE_SANDBOX.equals(authContext.getApiKey())) {
//Write logic to generate concurrent controller and throttle requests according to predefined way
}

Then users will throttle out when they invoke APIs with sandbox keys more than what they allowed with sandbox limits.

When they need to use APIs for production usage they need to go through production key generation approval process and admin user can decide what to do. If payment required or manual approval need we can handle it.

Then they can invoke APIs with production keys and invoke real back end. 

Introducing WSO2 API Manager New REST API for Store and Publisher Operations

$
0
0
In the API Manager 1.10 release, the API Manager team unveild a new REST API for store and publisher operations. This article will discuss the details of the REST API design, how it was developed, and how you can use the API to generate customized applications that can design, develop, manage, and consume APIs.

Table of Contents

  • Introduction
  • REST API Design and Implementation Details
  • Security Mechanisms
  • OAuth Application Registration
  • API Invocation
  • How to Write a Simple Java Client to Invoke Rest API and Get all APIs
  • Conclusion


Introduction

WSO2 API Manager is a complete solution for publishing APIs, creating and managing a developer community, and for scalably routing API traffic. It leverages proven, production-ready, integration, security and governance components from WSO2 Enterprise Service Bus, WSO2 Identity Server, and WSO2 Governance Registry. Moreover, it is powered by WSO2 Business Activity Monitor, thereby making WSO2 API Manager ready for any large-scale deployments right away.
As part of its latest release, the REST API was developed as a CXF REST web application running on WSO2 API Manager. This API comes with a pluggable security mechanism. API security is implemented as a CXF handler, hence if users need to plug custom security mechanism then they can write their own handler and add it to web service. This REST API is implemented based on REST best practices and specifications. The API development started with a swagger specification for store and publisher operations.
In today’s connected world, it’s important to have proper REST APIs for all available software products. Almost all organizations, platforms, and products are connected to each other via APIs to enable a better service. For instance, if you consider a solution like API Management, then a complete API is a must-have feature given that most times users will develop their own API store publisher using APIs that are available in the platform.
Prior to API manager 1.10, we had a Jaggery-based REST API for API Management related common operations; however, it was not fully compliant with REST specifications. Therefore, in the 1.10 version, we decided to implement a complete REST API that complies with all REST-related best practices. We also decided to follow the Richardson maturity model for REST API when we progressed with implementation.
In WSO2 API Manager, you can perform all operations available in the API store and publisher via REST API. From API Manager 1.10 onwards, the product will come with REST API store and publisher features. The API store and publisher Jaggery applications will still support the old REST API. However, if you’re using the WSO2 API Manager 1.10 version or above, it’s highly recommended to use the new REST API to all store and publisher operations.
The contract first approach is not a new design methodology to anyone in the software industry, and in this implementation too we’ve used this approach. We started with a swagger definition for REST APIs and then progressed to design a complete REST API using swagger API description language. When designing the API, we identified resources, resource URLs, and multiple parameters to be pass APIs. All input/output request format response codes, response body, etc. were designed using swagger. For the initial implementation, we’ve incorporated REST API for API store and publisher functionalities. In the future, we will introduce a new API for all management and other operations available in the product.
In the swagger definition, we defined data models for each and every resource object. Hence, each resource would be represented with JSON payload and we can then map them to a Java object. This article will discuss the basics in REST API design, development details, and how you can invoke it. To invoke this REST API, you can use any web service client available in the industry, such as Curl, REST Client, SoapUI, or any others.
With this API, you can make a developer’s’ life easy as it’s a well-defined API. Since we have a complete swagger definition, users can generate client applications using a swagger document or code generation clients based on WADL, e.g. a WADL to Java client.


REST API Design and Implementation Details

These two web applications are implemented as CXF web applications. For this, we used swagger to CXF client and generated a code for web application. As we are generating CXF server side skeleton code directly from the swagger definition, there is a minimal amount of gap between the swagger definition and the actual implementation. In addition, when we make a change to the specification, this can easily be brought into the implementation code. These are major advantages of using a code generator. Once the initial code was generated, we implemented a data access layer.
WSO2 API Manager store and publisher REST APIs are developed as 2 separate CXF web applications named as follows:
  • Applications are named as
  • api#am#store#v1.war and
  • api#am#publisher#v1.war.
  • Applications will be deployed in contexts
  • api/am/store/v1 and
  • api/am/publisher/v1.
These 2 APIs are developed based on swagger definitions for WSO2 API Manager store and publisher. This app development first started with the swagger API definition after identifying all required operations for the API management story. Then the swagger to CXF code generator was used to generate code for web applications. The underlying data access layer will directly call the API manager consumer and provider implementations.
For more details about all supporting methods in this rest API you can use the swagger console and add WSO2 API Manager store and publisher REST API definitions. Then it will list all operations available in store and publisher (you can find store and publisher swagger definitions for API Magere 1.10 in this git location.


Security Mechanisms

WSO2 API Manager REST API has complex resource paths for different operations. These resources should be accessible based on user permissions. In real production systems, you would need to be able to manage these permissions as extensively as possible as requirements can change based on user scenarios. Moreover, you should be able to easily add/update permissions per resource/operations and associated users/roles, etc.
For example, let’s consider the following requirement:
API update/edit can be performed only by a special user with API create/update permission; API lifecycle state changes should be carried out by a user who has API publish permission; and tier edit/update should be performed by users with administrative privileges.
Here, you can see that different resources are defined with different permissions and, depending on deployment, these permissions can be changed. As a solution for that requirement, API manager REST APIs will comprise extendable security mechanisms.
According to the current implementation, API manager REST API web applications contain CXF interceptors to handle security. By default, it will have 3 security related interceptors and users can change configuration and select the required mechanism. In summary, we will support the following security mechanisms for REST API:
  1. Basic authentication
  2. XACML for fine-grained permission validation
  3. OAuth with scopes support
If users are willing to have another security mechanism they need to write CXF handler and plug it to web applications. It’s always recommended to use one or more security mechanisms with this API as users can do almost all critical operations using these APIs.
You can change the CXF interceptor by editing WEB-INF/beans.xml files. You can see the following entry for the security interceptor.

As you can see above, by default, REST APIs come with OAuth authentication; if you need to change it to basic authentication you may change the auth handler as follows:

Then you need to pass basic authentication headers along with API calls.
If you are planning to use XACML as fine-grained permission validator, you may add XACML handler in the same way we discussed earlier.
When you hit the XACML flow you will get server URL, username, and password defined in Java code of EntitlementClientUtils class and create a XACML client. If users are willing to use XACML in production, it is recommended to use some kind of configuration file and read these properties from it when you create the XACML client. Thereafter, we will do a web service call to the XACML service that’s running on server using the already created client. To create the XACML policy, you may need to install XACML features into the API manager or use WSO2 Identity Server as the key validator.
For the initial release we will use hard-coded parameters to connect the XACML server and later we will provide additional configuration to be used by this interceptor. To understand XACML usage in API manager you can refer to this article - (http://wso2.com/library/articles/2014/02/use-of-wso2-api-manager-to-validate-fine-grained-policy-decisions-using-xacml/).
By default, OAuth has been enabled as a security mechanism for REST APIs. Refer to the following diagram to understand OAuth flow to obtain token and access APIs.
Figure 1


OAuth Application Registration

Dynamic client registration is a very common and widely used software security implementation. In this case, we have provided web application register Oauth applications using dynamic client registration protocol. However, it’s important to note that this is not a complete implementation of the dynamic client registration specification. In API manager, you will see that the web application has been named client-registration. It’s the CXF web application that’s directly calling the API manager key manager. From WSO2 API Manager 1.9.0 onward, you can plug your own key manager implementation to the API manager product. We have extracted the key manager interface and anyone can write their own implementation for it. We will reuse the same capability here as well. We do not rely on the underlying key manager implementation. We will simply request the key manager object and call its method based on a pre-defined interface for the key manager.
First we have to obtain consumer key/secret key pair by calling the dynamic client registration endpoint. Then you can request an access token with proffered grant type. When doing so, you have to provide scope according to your requirements. The above-mentioned steps are almost the same for the identity server use case as well. Resource registration was not required because we will be using the swagger document as the resource for API. The scope to role mapping will be stored as configuration defined in the /_system/config/apimgt/applicationdata/tenant-conf.json configuration file available in tenants configuration registry.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"RESTAPIScopes": {
  "Scope": [
    {
      "Name": "API_PUBLISHER_SCOPE",
      "Roles": "admin"
    },
    {
      "Name": "API_CREATOR_SCOPE",
      "Roles": "admin"
    },
    {
      "Name": "API_CREATOR_PUBLISHER_SCOPE",
      "Roles": "admin"
    },
    {
      "Name": "API_SUBSCRIBER_SCOPE",
      "Roles": "Internal/subscriber"
    },
    {
      "Name": "API_ADMINISTRATIVE_SCOPE",
      "Roles": "admin"
    }
  ]
}
Secured DCR end point with basic authentication
Now DCR is available as an installable feature, therefore anyone can install it and use it as per requirement. If you need to use it with the identity server, you can simply install this feature in the product.
Sample request to registration API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"callbackUrl": "www.google.lk",
"clientName": "rest_api_store",
"tokenScope": "Production",
"owner": "admin",
"grantType": "password refresh_token",
"saasApp": true
}
Sample response
{
"callBackURL": "www.google.lk",
"jsonString": "{\"username\":\"admin\",\"redirect_uris\":\"www.google.lk\",\"tokenScope\":[Ljava.lang.String;@3a73796a,\"client_name\":\"admin_rest_api_store\",\"grant_types\":\"authorization_code password refresh_token iwa:ntlm urn:ietf:params:oauth:grant-type:saml2-bearer client_credentials implicit\"}",
"clientName": null,
"clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa",
"clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa"
}


API Invocation

During the API invocation process request, first come to the CXF handler and then it will call an introspection API to validate the token. Post token validation, we will carry out scope validation with the given resource. To validate resources with scope, we will use the API object created by parsing the swagger document of API. Therefore, you don't need to store scopes/API details in databases. It will dynamically generate with swagger content (swagger inbuilt scope association for resources).
If you need to change the permission model, you just have to update swagger/configuration and redeploy application. To maintain scope to role mapping, we will use configuration defined in the WSO2 API Manager configuration file.
As of now we have identified 4 scopes to cover normal use cases:
  • API_PUBLISHER_SCOPE, publisher
  • API_SUBSCRIBER_SCOPE, subscriber
  • API_CREATOR_SCOPE, creator
  • API_ADMINISTRATIVE_SCOPE, admin
Token generate request
curl -k -d "grant_type=password&username=sanjeewa&password=sanjeewa&scope=API_SUBSCRIBER_SCOPE" -H "Authorization: Basic SGZFbDFqSlBkZzV0YnRyeGhBd3liTjA1UUdvYTpsNmMwYW9MY1dSM2Z3ZXpIaGM3WG9HT2h0NUFh" https://127.0.0.1:8243/token
Token response
1
2
3
{"scope":"API_SUBSCRIBER_SCOPE","token_type":"Bearer",
"expires_in":3600,"refresh_token":"33c3be152ebf0030b3fb76f2c1f80bf8",
"access_token":"292ff0fd256814536baca0926f483c8d"}


How to Write a Simple Java Client to Invoke REST API and Get all APIs

This section will focus on how you can implement Java client to invoke REST APIs. As discussed in previous section, API invocation is carried out in three steps. To register Oauth application, you would need to get an access token and invoke the API by using the following code sample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//Following code block will call dynamic client registration endpoint and register OAuth application
//Here getKeyManagerURLHttp should return URL of key management server (default http://127.0.0.1:9763)
 
String dcrEndpointURL =getKeyManagerURLHttp()+"client-registration/v1/register";
 
//This is the app request body. You can create JSON payload with your details for app.
 
String applicationRequestBody = " {\n" +
" \"callbackUrl\": \"www.google.lk\",\n" +
" \"clientName\": \"fffff\",\n" +
" \"tokenScope\": \"Production\",\n" +
" \"owner\": \"admin\",\n" +
" \"grantType\": \"password refresh_token\",\n" +
" \"saasApp\": true\n" +
" }";
Map<string, string=""> dcrRequestHeaders = new HashMap<string, string="">();
//This is base 64 encoded basic Auth value for user name admin and password admin.
String basicAuthHeader = "admin" + ":" + "admin";
byte[] encodedBytes = Base64.encodeBase64(basicAuthHeader.getBytes("UTF-8"));
dcrRequestHeaders.put("Authorization", "Basic " + new String(encodedBytes, "UTF-8"));
//Set content type as its mandatory for API
dcrRequestHeaders.put("Content-Type", "application/json");
JSONObject clientRegistrationResponse =new JSONObject(HttpRequestUtil.doPost(new URL(dcrEndpointURL), applicationRequestBody,dcrRequestHeaders));
 
//Now you have consumer key and secret key obtained from client registration call.
//Let's extract these parameters from response message as follows:
 
String consumerKey =new JSONObject(clientRegistrationResponse.getString("data")).get("clientId").toString();
String consumerSecret =new JSONObject(clientRegistrationResponse.getString("data")).get("clientSecret").toString();
Thread.sleep(2000);
 
//Now we need to call token API and request access token.
//For this example we will use password grant type. You need to pass correct scope based on the resource you are trying to access.
 
String requestBody = "grant_type=password&username=admin&password=admin&scope=API_CREATOR_SCOPE";
 
//Calling token endpoint and get access token (default token endpoint URL would be http://127.0.0.1:8280/token)
 
URL tokenEndpointURL = new URL(getGatewayURLNhttp() + "token");
JSONObject accessTokenGenerationResponse = new JSONObject(
apiStore.generateUserAccessKey(consumerKey, consumerSecret, requestBody,
tokenEndpointURL).getData()
);
 
//Add consumer key and secret as basic auth header
Map<string, string=""> authenticationRequestHeaders = new HashMap<string, string="">();
String basicAuthHeader = consumerKey + ":" + consumerSecret;
byte[] encodedBytes = Base64.encodeBase64(basicAuthHeader.getBytes("UTF-8"));
authenticationRequestHeaders.put("Authorization", "Basic " + new String(encodedBytes, "UTF-8"));
JSONObject accessTokenGenerationResponse= new JSONObject(HttpRequestUtil.doPost(tokenEndpointURL, requestBody, authenticationRequestHeaders));
 
//Get access token and refresh token from token API call.
//Now we have access token and refresh token that we can use to invoke API.
 
String userAccessToken = accessTokenGenerationResponse.getString("access_token");
String refreshToken = accessTokenGenerationResponse.getString("refresh_token");
Map<string, string=""> requestHeaders = new HashMap<string, string="">();
//Check User Access Token
requestHeaders.put("Authorization", "Bearer " + userAccessToken);
requestHeaders.put("accept", "text/xml");
 
//Call API publisher REST API and get all registered APIs in system. This will return you API array in json format.
HttpRequestUtil.doGet(getKeyManagerURLHttp()+"/api/am/publisher/v1/apis?query=admin&type=provide",requestHeaders);
</string,></string,></string,></string,></string,></string,>


Conclusion


In this article, we’ve taken you through a quick introduction into the concepts, implementation details, and how to use API manager REST API. Being aware of REST API is beneficial in terms of either building applications that consume WSO2 API Manager APIs or just a WSO2 API Manager user. Exposing API manager resources via a RESTful API is a flexible way to expose services to the outside world. It helps to meet integration requirements of an API management platform as well as external applications/systems. The details discussed in this article cover just the basics, but is aimed at inspiring you to develop your own application using API manager REST API.

How to enable consent for scopes when you get oauth2 access token for API Manager applications(authorization code flow) - Identity Server 5.3 and above API Manager 2.0.0

$
0
0
During the process of obtaining an auth code, the end user is prompted with something like after he/she logs in: "user_DefaultApplication_PRODUCTION requests access to your profile information". 
 However it does not mention the scope(s) that the end user is about to grant access to. So users do not know what are the scopes they granted when they generate access tokens.
So we do have identified showing and get user consent for scopes as valid requirement. Then created JIRA to fix this issue in upcoming identity server release(5.3.0). Once identity components release with this feature API Manager can use it and next API Manager release will have that. Once we have that feature you can do following changes in authentication endpoint app and get user consent for scopes.
/repository/deployment/server/webapps/ directory. You'll see the exploded directory authenticationendpoint. Then users can edit web.xml file in authenticationendpoint/WEB-INF directory and displayScopes parameter to true and save the file.

<context-param>
<param-name>displayScopes</param-name>
<param-value>true</param-value>
</context-param>
Once the change is done, you'll see an entry in the carbon log similar to Reloaded Context with name: /authenticationendpoint after a couple of seconds. The scopes will be displayed in the consent page afterwards.

How to handle authentication failures from custom authentication handler - WSO2 API Manager

$
0
0
When we are implementing a custom Authentication Handler for wso2 API Manager we need to handle the case when authentication handler returns false. That mean authentication got failed and we need to send error back to client. Following is the sample code of the handleRequest method.
public boolean handleRequest(MessageContext messageContext) {
    try {
        if (authenticate(messageContext)) {
            return true;
        }
        else{
          //Your logic should go here.
        }
    } catch (APISecurityException e) {
        e.printStackTrace();
    }
    return false;
}

Ideally you need to call handleAuthFaliure method with message context.

private void handleAuthFailure(MessageContext messageContext, APISecurityException e) 

When you call that method please create APISecurityException object(as listed below) and pass it. Then error code and error messages will be picked from there and automatically send error to client(by default we return 401 for security exceptions and if defined then send defined error code and message).

public class APISecurityException extends Exception {
    private int errorCode;
    public APISecurityException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    public APISecurityException(int errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }
    public int getErrorCode() {
        return errorCode;
    }
}
As you may already know you can generate error within your code and sent it back to client. But since API Manager have this capability you can easily use this without writing your own logic. And another advantage is if you pass error like this then it will go through auth_faliure_handler sequence and you can do any transformation there in a way it effect to all authentication failures.

How to create axis2 service repository using WSO2 Governance Registry

$
0
0
Sometimes we need to store all service metadata in single place and maintain changes, life cycles etc. To address this we can implement this as automated process. In this example i will specifically focus on axis2 services and discuss how to create service repository for axis 2 services.

Here is the detailed flow.
  • In jenkins(or any other task scheduler to check available services frequentrly) we will deployed scheduled task to trigger some event periodically.
  • Periodic task will call WSO2 App Server’s admin services to get service metadata. To list service meta data for axis2 services we can call service admin soap service (https://127.0.0.1:9443/services/ServiceAdmin?wsdl)
  • In same way we can call all services and get complete service data(if you need other service types in addition to axis2 services).
  • Then we can call registry rest API and push that information.  Please refer this article for more information about Registry REST API.  

If we consider proxy service details then we can follow approach listed below.
Create web service client for https://127.0.0.1:9443/services/ServiceAdmin?wsdl service and invoke it from client. See following Soapui sample to get all proxy services deployed in ESB.



You will see response like below. There you will all details related to given proxy service such as wsdls, service status, service type etc. So you can list all service metadata using the information we retrieved from this web service call.


<soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:listServicesResponsexmlns:ns="http://org.apache.axis2/xsd">
<ns:returnxsi:type="ax2356:ServiceMetaDataWrapper"
xmlns:ax2356="http://mgt.service.carbon.wso2.org/xsd"
xmlns:ax2358="http://neethi.apache.org/xsd"xmlns:ax2359="http://util.java/xsd"
xmlns:ax2354="http://utils.carbon.wso2.org/xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ax2356:numberOfActiveServices>4</ax2356:numberOfActiveServices>
<ax2356:numberOfCorrectServiceGroups>4</ax2356:numberOfCorrectServiceGroups>
<ax2356:numberOfFaultyServiceGroups>0</ax2356:numberOfFaultyServiceGroups>
<ax2356:numberOfPages>1</ax2356:numberOfPages>
<ax2356:serviceTypes>axis2</ax2356:serviceTypes>
<ax2356:serviceTypes>js_service</ax2356:serviceTypes>
<ax2356:servicesxsi:type="ax2356:ServiceMetaData">
<ax2356:active>true</ax2356:active>
<ax2356:descriptionxsi:nil="true"/>
<ax2356:disableDeletion>false</ax2356:disableDeletion>
<ax2356:disableTryit>false</ax2356:disableTryit>
<ax2356:eprsxsi:nil="true"/>
<ax2356:foundWebResources>false</ax2356:foundWebResources>
<ax2356:mtomStatusxsi:nil="true"/>
<ax2356:name>echo</ax2356:name>
<ax2356:operationsxsi:nil="true"/>
<ax2356:scopexsi:nil="true"/>
<ax2356:securityScenarioIdxsi:nil="true"/>
<ax2356:serviceDeployedTime>1970-01-01 05:30:00</ax2356:serviceDeployedTime>
<ax2356:serviceGroupName>Echo</ax2356:serviceGroupName>
<ax2356:serviceIdxsi:nil="true"/>
<ax2356:serviceType>axis2</ax2356:serviceType>
<ax2356:serviceUpTime>17023day(s) 6hr(s) 16min(s)</ax2356:serviceUpTime>
<ax2356:serviceVersionxsi:nil="true"/>
<ax2356:tryitURL>http://172.17.0.1:9763/services/echo?tryit</ax2356:tryitURL>
<ax2356:wsdlPortTypesxsi:nil="true"/>
<ax2356:wsdlPortsxsi:nil="true"/>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/echo?wsdl</ax2356:wsdlURLs>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/echo?wsdl2</ax2356:wsdlURLs>
</ax2356:services>
<ax2356:servicesxsi:type="ax2356:ServiceMetaData">
<ax2356:active>true</ax2356:active>
<ax2356:descriptionxsi:nil="true"/>
<ax2356:disableDeletion>false</ax2356:disableDeletion>
<ax2356:disableTryit>false</ax2356:disableTryit>
<ax2356:eprsxsi:nil="true"/>
<ax2356:foundWebResources>false</ax2356:foundWebResources>
<ax2356:mtomStatusxsi:nil="true"/>
<ax2356:name>HelloService</ax2356:name>
<ax2356:operationsxsi:nil="true"/>
<ax2356:scopexsi:nil="true"/>
<ax2356:securityScenarioIdxsi:nil="true"/>
<ax2356:serviceDeployedTime>1970-01-01 05:30:00</ax2356:serviceDeployedTime>
<ax2356:serviceGroupName>HelloWorld</ax2356:serviceGroupName>
<ax2356:serviceIdxsi:nil="true"/>
<ax2356:serviceType>axis2</ax2356:serviceType>
<ax2356:serviceUpTime>17023day(s) 6hr(s) 16min(s)</ax2356:serviceUpTime>
<ax2356:serviceVersionxsi:nil="true"/>
<ax2356:tryitURL>http://172.17.0.1:9763/services/HelloService?tryit</ax2356:tryitURL>
<ax2356:wsdlPortTypesxsi:nil="true"/>
<ax2356:wsdlPortsxsi:nil="true"/>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/HelloService?wsdl</ax2356:wsdlURLs>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/HelloService?wsdl2</ax2356:wsdlURLs>
</ax2356:services>
<ax2356:servicesxsi:type="ax2356:ServiceMetaData">
<ax2356:active>true</ax2356:active>
<ax2356:descriptionxsi:nil="true"/>
<ax2356:disableDeletion>false</ax2356:disableDeletion>
<ax2356:disableTryit>false</ax2356:disableTryit>
<ax2356:eprsxsi:nil="true"/>
<ax2356:foundWebResources>false</ax2356:foundWebResources>
<ax2356:mtomStatusxsi:nil="true"/>
<ax2356:name>Version</ax2356:name>
<ax2356:operationsxsi:nil="true"/>
<ax2356:scopexsi:nil="true"/>
<ax2356:securityScenarioIdxsi:nil="true"/>
<ax2356:serviceDeployedTime>1970-01-01 05:30:00</ax2356:serviceDeployedTime>
<ax2356:serviceGroupName>Version</ax2356:serviceGroupName>
<ax2356:serviceIdxsi:nil="true"/>
<ax2356:serviceType>axis2</ax2356:serviceType>
<ax2356:serviceUpTime>17023day(s) 6hr(s) 16min(s)</ax2356:serviceUpTime>
<ax2356:serviceVersionxsi:nil="true"/>
<ax2356:tryitURL>http://172.17.0.1:9763/services/Version?tryit</ax2356:tryitURL>
<ax2356:wsdlPortTypesxsi:nil="true"/>
<ax2356:wsdlPortsxsi:nil="true"/>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/Version?wsdl</ax2356:wsdlURLs>
<ax2356:wsdlURLs>http://172.17.0.1:9763/services/Version?wsdl2</ax2356:wsdlURLs>
</ax2356:services>
</ns:return>
</ns:listServicesResponse>
</soapenv:Body>
</soapenv:Envelope>


We can automate this service metadata retrieving process and persist it to registry. Please refer below diagram to understand flow for this use case. Discovery agent will communicate with servers and use REST client to push events to registry.

Untitled drawing(1).jpg

How to use Java scrip mediator to modify outgoing message body during mediation flow - WSO2 ESB/ API Manager

$
0
0
Here in this post we will see how we can use Java scrip mediator to modify outgoing message body during mediation flow.
Below is the sample API configuration i used for this sample. As you can see here i will extract password field from incoming message and send it as symbol to back end service. Since i need to check what actually pass to back end server i added TCPMon between gateway and back end server. That is why 8888 port is appear there. 
<apiname="TestAPI"context="/test">
<resourcemethods="POST"url-mapping="/status"faultSequence="fault">
<inSequence>
<scriptlanguage="js">var symbol = mc.getPayloadXML()..*::password.toString();
mc.setPayloadXML(
&lt;m:getQuote xmlns:m="http://services.samples/xsd"&gt;
&lt;m:request&gt;
&lt;m:symbol&gt;{symbol}&lt;/m:symbol&gt;
&lt;/m:request&gt;
&lt;/m:getQuote&gt;);</script>
<send>
<endpointname="test-I_APIproductionEndpoint_0">
<httpuri-template="http://127.0.0.1:8888/"/>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
</api>
Then i send request as follows. As you can see here password will have some data and i'm sending post request.
curl -v -X POST -H "Content-Type: application/json"-d '{"username":"xyz","password":"xyz & abc"}' http://127.0.0.1:8280/test/status
I can see my values pass to back end properly. Since i added TCPMon between ESB and back end to verify out going message i can see what going out from ESB. Also following is wore logs captured for my message.
[2016-08-1014:30:21,236] DEBUG - wire >>"POST /test/status HTTP/1.1[\r][\n]"
[2016-08-1014:30:21,236] DEBUG - wire >>"Host: 127.0.0.1:8280[\r][\n]"
[2016-08-1014:30:21,236] DEBUG - wire >>"User-Agent: curl/7.43.0[\r][\n]"
[2016-08-1014:30:21,236] DEBUG - wire >>"Accept: */*[\r][\n]"
[2016-08-1014:30:21,236] DEBUG - wire >>"Content-Type: application/json[\r][\n]"
[2016-08-1014:30:21,236] DEBUG - wire >>"Content-Length: 41[\r][\n]"
[2016-08-1014:30:21,237] DEBUG - wire >>"[\r][\n]"
[2016-08-1014:30:21,237] DEBUG - wire >>"{"username":"xyz","password":"xyz & abc"}"
[2016-08-1014:30:21,245] DEBUG - wire <<"POST /status HTTP/1.1[\r][\n]"
[2016-08-1014:30:21,245] DEBUG - wire <<"Content-Type: application/json[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"Accept: */*[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"Transfer-Encoding: chunked[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"Host: 127.0.0.1:8888[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"Connection: Keep-Alive[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"User-Agent: Synapse-PT-HttpComponents-NIO[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"[\r][\n]"
[2016-08-1014:30:21,246] DEBUG - wire <<"2f[\r][\n]"
[2016-08-1014:30:21,247] DEBUG - wire <<"{"getQuote":{"request":{"symbol":"xyz & abc"}}}[\r][\n]"
[2016-08-1014:30:21,247] DEBUG - wire <<"0[\r][\n]"
[2016-08-1014:30:21,247] DEBUG - wire <<"[\r][\n]"

TCPMon output.













How to manage multiple API Manager instances for different environment and use single external key Management server - WSO2 API Manager

$
0
0
Here i'm explaining solution for manage multiple API Manager environments and external key management server to build central API repository. Gateways in each environment can talk to different key managers as its just pointing key validation URLs.  In store we do not have concept of showing multiple consumer key/secret access tokens per environment. 
But like we discussed early we are using external key Manager as underlying key Manager and use it from WSO2 key Managers and gateways. So if we designed to have same application in store irrespective deployment it deployed we can achieve this requirement.

We have one API which can deployed in multiple environments. But can only one subscription for all environments and same set of tokens will work any environment. Still each environment have their own key manager and when it comes to validate again direct to same external key manager.

To understand more about API publisher publishing to multiple environment please refer this article.
https://docs.wso2.com/display/AM200/Maintaining+Separate+Production+and+Sandbox+Gateways

To study about deploying same API across multiple environments and URL to automatically resolve based on deployment refer this article.
http://sanjeewamalalgoda.blogspot.com/2016/07/how-to-define-environment-specific-url.html
http://nuwanzone.blogspot.com/2015/03/api-gateways-with-dedicated-back-ends.html

External key manager concept and more details.
https://docs.wso2.com/display/AM190/Configuring+a+Third-Party+Key+Manager

Display multiple gateway URLs in API store can achieve with external gateway concept.
Please refer following diagram for complete solution.


WSO2 API Manager based solutions frequently asked questions and answers for them - 01

$
0
0
OAuth support for REST API and WS-security token for SOAP/XML?
OAuth 2.0 support for REST API is available in WSO2 product platform. WS security, basic auth, xacml and other common authentication authorization implementations available in WSO2 solution and users can use them.

Support HMAC header signature or OAuth for REST API and WS-security message signature for SOAP service?
HMAC header signature validation and verification need to implement as separate handler and engage to API. That is not available as a OOTB solution. Both requirements can be fulfilled by writing a custom extension.

Support HTTPS for REST and ws-security message encryption for SOAP?
WSO2 supports WS Security and WS-Policy specifications. These specifications define a behavioral model for web services. A requirement for one proxy service may not be valid for another. Therefore, WSO2 provides the option to define service specific requirements. Security functionality is provided by the Security Management feature which is bundled by default in the Service Management feature of the WSO2 feature repository. The Security Management feature makes it easy to secure the proxy services of the ESB by providing twenty pre-defined, commonly-used security scenarios. These security policies are disabled by default.
https://docs.wso2.com/display/ESB481/Securing+Proxy+Services

Can safely publish APIs to external mobile applications?
Supported, APIs can be exposed to external mobile applications for consumption. Similarly a separate gateway can expose APIs for internal consumption as well.

Is it possible to integrate with external log systems or analyzing frameworks?
Users need to write custom log agent or use syslog agent to integrate with external tools. We have done similar integrations previously and use syslog agent for that.

Is it supports the 'API First' design with capabilities to publish API interfaces and/or import Swagger 2.0 definition(s)?
API first design capability is support with Swagger 2.0. It is possible to upload or refer a Swagger document and create the API based on this Swagger document.

Capability to support established open API documentation frameworks?
Supported, Swagger based documentation is supported. It is possible to create APIs based on a Swagger document. It is also possible to interactively test APIs through Swagger.

Can we deploy a prototyped API quickly without actual back end system?
"It is possible to deploy a new API or a new version of an existing API as a prototype.  It gives subscribers an early implementation of the API that they can try out without a subscription or monetization. Similarly in case if the actual back end service implementation is not available it is possible to create mock responses that can be sent as a response for API requests.
https://docs.wso2.com/display/AM200/Deploy+and+Test+as+a+Prototype"

Capability to browse and search APIs by provider, tag, name?
Supported, it is possible to search APIs and associated documentation as well as tag and filter APIs available in the portal.

Provides a developer portal with dashboard, subscription to API,  provisioning API keys capabilities & tokens?
API store (developer portal) provides a dashboard from which developers can  search, subscribe, generate API keys, rate and review APIs and view usage statistics from the API Store.

How API Manager supports community engagement with capabilities?
API Store (developer portal) allows users to self sign-up which can even be linked to an approval process where an authorized user's needs to approve the sign up before a user is allowed to access the portal. Users are able to view usage statistics, contribute towards the user forum, comment/review and rate APIs.

Capability to publish APIs to internal users only, external partners only and all users?
Supported, API visibility and subscription availability can be restricted based on user roles and tenants (if the API Manager is deployed in the multi-tenant mode).

Capability to provision API keys on demand?
Supported, API keys can be provisioned by users on-demand via the API Store or through the provided RESTful API.

Supports publishing and deploying APIs to multiple API Gateways?
Supported, it is possible to publish an API to a selected Gateway or to multiple Gateways. https://docs.wso2.com/display/AM200/Publish+through+Multiple+API+Gateways

WSO2 API Manager based solutions frequently asked questions and answers for them - 02

$
0
0
Capability to create, manage and deploy both sandbox environments and production environments?
It is possible to manage a Sandbox and a Production environment simultaneously. Each of these environments can have its own API Gateway.

Can deploy application(s)/project(s) from one environment to another environment?
Applications and subscriptions cannot be migrate from one environment to another directly. But a RESTful API is available to get a list of applications and recreate them in another environment. However APIs can be imported/exported from one environment to another OOTB.

Capability to apply throttling to APIs and route the calls for different API endpoints?
Supported, Throttling can be applied to APIs based on a simple throttling rule such as number of requests allowed per minute or based on a complex rule which can consider multiple parameters such as payload size and requests per minute when throttling API calls.
API Gateway can apply throttling policies for different APIs and route the API calls for the relevant back end.

Supports  various versioning including URL, HTTP header, and Query parameter(s)?
API Manager supports URL based versioning strategy. If need we can implement our own

Capability to support API life cycle management including 'create', 'publish', 'block', and 'retire' activities?
API life cycle can be managed by the API Manager. By default it supports Created, Published, Depreciated, Blocked and Retired stages.

Can it manage API traffic by environments (i.e. sandbox, production etc.) and by Gateway?
Supported,Multiple API Gateways can be setup for Sandbox and Production environments to handle traffic of each environment separately. https://docs.wso2.com/display/AM200/Maintaining+Separate+Production+and+Sandbox+Gateways

Does it have throttling limit support?
Supported, Throttling enables users to create more complex policies by mixing and matching different attributes available in the message. Moreover, it supports throttling scenarios based on almost all header details. WSO2 API Manager 2.0 offers more flexibility when it comes to defining rules. In addition, the blocking feature will be very useful as well to protect servers from common attacks and abuse by users.

Provides rate limiting support?
Supported, rate limit support is available in the API Manager.

Capability to horizontally scale traffic in a clustered environment
Supported, a API Manager instance can handle over 3500 transactions per second when its fully optimized.

Support local caching for API responses (i.e. in non-clustered environment or when clustering not activated)?
Supported, it is possible to enable or disable API response caching for each API exposed.

Support distributed caching for API responses amongst nodes within a cluster?
Supported, caching is distributed to all Gateway nodes in the cluster.

Capability of auto-scaling via adding new nodes based on load ( i.e. auto spawning new instances and add to cluster)?
Autoscaling should be supported at underlying infrastructure level. The cluster allows any new node to join or leave the cluster whenever required.

Supports conversion from SOAP to REST?
Supported, SOAP to REST conversion is supported

Supports conversion from XML to JSON and JSON to XML within request and response payloads?
Supported, it is possible to convert the request and payload from XML to JSON and vice versa.
https://docs.wso2.com/display/AM200/Convert+a+JSON+Message+to+SOAP+and+SOAP+to+JSON

Supports redirecting API calls via the rewriting of URLs?
URL rewriting is supported with this it is possible to change final API destination dynamically based on a predefined condition and route requests. It is also possible to define parameterized URLs which can resolve a value in runtime according to an environment variable.

Ability to parse inbound URL for params including query parameters?
Supported, Query parameter, path parameter reading and modifications can be done before a request is sent to the backend.

Visual development, rapid mapping of activities and data?
Visual development and visual data mapper is available to develop the mediation sequences required. The visual development would be done via WSO2 Developer Studio which an Eclipse based IDE.

Custom activity - define custom code with input/output interface?
Supported, Custom code can be written as Java or Java scripts.

WSO2 API Manager based solutions frequently asked questions and answers for them - 03

$
0
0
Can API Manager audit a source request IP address, and the user who made the request?
Yes, information on the request IP and user is captured and can be logged to a report.

Automation support for API setup and for configuring the API gateway?
Supported, setup can be automated through tools like Puppet. Puppet for common deployment patterns are also available for download.

Capability to run reports on API usage, call volume, latency, etc? 
Supported, API usage, call volume and latency can be reported. However information on caching is not reported.

Logging support and capability to integrate with 3rd party logging module?
By default our products use log4j for logging and if need we can plug custom log appenders. It is possible to push logs to an external system as well.

Billing and payment support & monitoring tools for API usage?
Billing and payment integration support is not available OOTB. But extension points are available to integrate with an external billing and payment systems. Currently WSO2 API Cloud (SaaS offering of WSO2 API Manager) is integrated with payment system successfully. So users can implement required extensions and get the job done.

Capability of message processing cycle control via pre/post processing?
Supported, it is possible to do some pre/post processing of messages based on what is available OOTB, however some pre/post processing would require custom capabilities to be written.

Does it support adapters or connectors to 3rd party systems such as Salesforce etc.
Supported by WSO2 ESB, WSO2 Integration Platform provides connectors to over 130 3rd party systems including Salesforce.com. The entire list of connectors can be accessed and downloaded from the following site.
https://store.wso2.com/store/assets/esbconnector"

Capability of monitoring and enforcing policy (i.e. message intercept).
Supported, it is possible to validate the message against a XSD to ensure that its compliant with a schema definition, it is also possible to audit and log messages and manage overall security by enforcing WS-Security on messages.

Multiple technology database support?
Database connectivity is provided via a JDBC adapter and multiple JDBC adapters can be used at the same-time. It is possible to change from one database technology to another as long as a JDBC adapter is available.

Fail over Traffic Manager data receiver pattern for API Gateway.

$
0
0
The idea behind fail over data receiver endpoint is stopping single-point-of-failure in a system. As the broker deployed in each traffic manager and storing and forwarding the messages, if that server goes down entire message flowing of the system will go down no matter what other servers and functions are involved. Thus in order to make a robust messaging system it is mandatory to have a fail-over mechanism.

When we have few instances of Traffic Manager servers up and running in the system generally each of these server is having brocker. If one broker goes down then gateway automatically switch to the other broker and continue throttle message receiving. If that one also fails it will try next and so on. Thus as a whole system will not have a downtime.

So in order to achieve high availability for data receiving side we need to configure JMSConnectionParameters to connect multiple broker running within each traffic manager. So for that we need add following configuration to each gateway. If single gateway is communicating with multiple traffic manager this is the easiest way to configure gateway to communicate with multiple traffic managers.

To configure that you need to add following configuration to each gateway worker. Then it will pick updates from any of the traffic manager event if some of them not functioning.

<JMSConnectionParameters>              
<transport.jms.ConnectionFactoryJNDIName>TopicConnectionFactory</transport.jms.ConnectionFactoryJNDIName>
<transport.jms.DestinationType>topic</transport.jms.DestinationType>           
<java.naming.factory.initial>org.wso2.andes.jndi.PropertiesFileInitialContextFactory</java.naming.factory.initial>            
<connectionfactory.TopicConnectionFactory>amqp://admin:admin@clientID/carbon?failover='roundrobin'%26cyclecount='2'%26brokerlist='tcp://127.0.0.1:5673?
retries='5'%26connectdelay='50';tcp://127.0.0.1:5674?
retries='5'%26connectdelay='50''</connectionfactory.TopicConnectionFactory>
</JMSConnectionParameters>

Deploy multiple traffic managers with fail over data publisher fail over data receiver pattern.

$
0
0

Like we discussed early gateway data receiver need to configure with fail over data receiver. But data publisher can be configured according to load balance or failover pattern. In this section we will see how we can publish throttling events to traffic manager in failover pattern.

Failover configuration

s8YuuoU022qL8M0comFZBpA.png

When using the failover configuration in publishing events to Traffic manager, events are sent to multiple Traffic Manager receivers in a sequential order based on priority. You can specify multiple Traffic Manager receivers so that events can be sent to the next server in the sequence in a situation where they were not successfully sent to the first server. In the scenario depicted in the above image, first events are sent to Traffic Manager Receiver-1. If it is unavailable, then events will be sent to Traffic Manager Receiver-2. Further, if that is also available, then events will be sent to Traffic Manager Receiver-3.


<DataPublisher>
           <Enabled>true</Enabled>
           <Type>Binary</Type>
           <ReceiverUrlGroup>tcp://127.0.0.1:9612 | tcp://127.0.0.1:9613</ReceiverUrlGroup>
           <!--ReceiverUrlGroup>tcp://${carbon.local.ip}:9612</ReceiverUrlGroup-->
           <AuthUrlGroup>ssl://127.0.0.1:9712 | ssl://127.0.0.1:9713</AuthUrlGroup>
           <!--AuthUrlGroup>ssl://${carbon.local.ip}:9712</AuthUrlGroup-->
           <Username>${admin.username}</Username>
           <Password>${admin.password}</Password>
           <DataPublisherPool>
               <MaxIdle>1000</MaxIdle>
               <InitIdleCapacity>200</InitIdleCapacity>
           </DataPublisherPool>
           <DataPublisherThreadPool>
               <CorePoolSize>200</CorePoolSize>
               <MaxmimumPoolSize>1000</MaxmimumPoolSize>
               <KeepAliveTime>200</KeepAliveTime>
           </DataPublisherThreadPool>
       </DataPublisher>
          
<JMSConnectionParameters>              
<transport.jms.ConnectionFactoryJNDIName>TopicConnectionFactory</transport.jms.ConnectionFactoryJNDIName>
<transport.jms.DestinationType>topic</transport.jms.DestinationType>           
<java.naming.factory.initial>org.wso2.andes.jndi.PropertiesFileInitialContextFactory</java.naming.factory.initial>            
<connectionfactory.TopicConnectionFactory>amqp://admin:admin@clientID/carbon?failover='roundrobin'%26cyclecount='2'%26brokerlist='tcp://127.0.0.1:5673?
retries='5'%26connectdelay='50';tcp://127.0.0.1:5674?
retries='5'%26connectdelay='50''</connectionfactory.TopicConnectionFactory>
</JMSConnectionParameters>

Deploy multiple traffic managers with load balance data publisher failover data receiver pattern.

$
0
0

Load balancing events to a set of servers

Copy of Copy of traffic-manager-deployment-LBPublisher-failoverReciever(1).png

This setup shows load balancing the event to publish it to all Traffic Manager receivers. The load balanced publishing is done in a Round Robin manner, sending each event to each receiver in a circular order without any priority. It also handles fail-over cases such as, if Traffic Manager Receiver-1 is marked as down, then the Data Agent will send the data only to Traffic Manager Receiver-2(and if we have more node then for all of them) in a round robin manner. When Traffic Manager Receiver-1 becomes active after some time, the Data Agent automatically detects it, adds it to the operation, and again starts to load balance between all receivers. This functionality significantly reduces the loss of data and provides more concurrency.

For this functionality, include the server URL in the Data Agent as a general DAS/CEP receiver URL. The URL should be entered in a comma separated format as shown below.

<DataPublisher>
           <Enabled>true</Enabled>
           <Type>Binary</Type>
           <ReceiverUrlGroup>tcp://127.0.0.1:9612,tcp://127.0.0.1:9613</ReceiverUrlGroup>
           <AuthUrlGroup>ssl://127.0.0.1:9712,ssl://127.0.0.1:9713</AuthUrlGroup>
           <Username>${admin.username}</Username>
           <Password>${admin.password}</Password>
           <DataPublisherPool>
               <MaxIdle>1000</MaxIdle>
               <InitIdleCapacity>200</InitIdleCapacity>
           </DataPublisherPool>
           <DataPublisherThreadPool>
               <CorePoolSize>200</CorePoolSize>
               <MaxmimumPoolSize>1000</MaxmimumPoolSize>
               <KeepAliveTime>200</KeepAliveTime>
           </DataPublisherThreadPool>
       </DataPublisher>

Deploy multiple traffic managers with load balance data publisher failover data receiver pattern.

$
0
0

Load balancing events to sets of servers  

Copy of traffic-manager-deployment-LBPublisher-failoverReciever(3).png


In this setup there are two group of servers that are referred to as Group A and Group B. You can send events to both the groups. You can also carry out load balancing for both sets as mentioned in load balancing between a set of servers. This scenario is a combination of load balancing between a set of servers and sending an event to several receivers. An event is sent to both Group A and Group B. Within Group A, it will be sent either to Traffic Manager -01 or Traffic Manager -02. Similarly within Group B, it will be sent either to Traffic Manager -03 or Traffic Manager -04. In the setup, you can have any number of Groups and any number of Traffic Managers (within group) as required by mentioning them accurately in the server URL.

Similar to the other scenarios, you can describe this as a receiver URL. The Groups should be mentioned within curly braces separated by commas. Furthermore, each receiver that belongs to the group, should be within the curly braces and with the receiver URLs in a comma separated format. The receiver URL format is given below.

<DataPublisher>
           <Enabled>true</Enabled>
           <Type>Binary</Type>    <ReceiverUrlGroup>{tcp://127.0.0.1:9612,tcp://127.0.0.1:9613},{tcp://127.0.0.2:9612,tcp://127.0.0.2:9613} </ReceiverUrlGroup>
<AuthUrlGroup>{ssl://127.0.0.1:9712,ssl://127.0.0.1:9713}, {ssl://127.0.0.2:9712,ssl://127.0.0.2:9713}</AuthUrlGroup>
           <Username>${admin.username}</Username>
           <Password>${admin.password}</Password>
           <DataPublisherPool>
               <MaxIdle>1000</MaxIdle>
               <InitIdleCapacity>200</InitIdleCapacity>
           </DataPublisherPool>
           <DataPublisherThreadPool>
               <CorePoolSize>200</CorePoolSize>
               <MaxmimumPoolSize>1000</MaxmimumPoolSize>
               <KeepAliveTime>200</KeepAliveTime>
           </DataPublisherThreadPool>
       </DataPublisher>

Viewing all 220 articles
Browse latest View live