Tuesday, October 3, 2017

Whitelisting and Blacklisting IPs for APIs in API Manager

Most of the time we come across different scenarios where we need to,
  • Whitelist an IP for an API (Limiting API access for a given IP only)
  • Blacklisting an IP for an API (Blocking API access for a given IP/Ips only)
WSO2 API Manager 2.0.0 and 2.1.0 allows you to achieve whitelisting/blacklisting via the features provided by WSO2 API Traffic Manager.

Let's look into both use cases and how to come up with a solution via API manager.

Whiltelisting an IP

Suppose you want to restrict the API for IP with address '10.100.5.103' and block access to all other IPs. We can use an advanced throttling policy to achieve this. Please follow below steps.

1. Log in to the Admin Portal using the URL https://localhost:9443/admin and your admin credentials.

2. Select Throttling Policies > Advanced Throttling Policies 

      

3. To add a new tier, click Add Tier 













4. Fill in the basic details like tier name, descriptions and click Add Conditional Group to add throttling conditions to the policy.
























5. Click on conditional group to add conditional group details.






6. Fill the condition group details. In that case, you need to enable IP condition and specify the IP that you need to whitelist. Once the invert condition is enabled and set the throttling limit to be 0 then none of the requests coming from IPs other than the whitelisting IP will be served by gateway. After filling the details, click save. 




Now the policy is created successfully and you need to engage this policy with a particular API that you need to whitelist.

For that,
1. Login to API Publisher http://localhost:9443/publisher

2. In the 'Manage' tab of API create/update window, enable advanced throttling for API and select throttling policy that we have created before.















3. Save and Publish API

Now the API will be accessible only by the IP/IPs specified in throttling policy.

Note: Since it takes some time to deploy the policy, the first few requests from the IPs other that the whitelisted IP/IPs will be allowed to pass through. After the policy is successfully deployed, non whitelisted IP access will be blocked.

Blacklisting an IP

Please refer to https://docs.wso2.com/display/AM210/Managing+Throttling#ManagingThrottling-Blacklistingrequests on how to blacklist an IP

    Sunday, July 3, 2016

    One time download link for mobile app download in App Manager

    In App Manager 1.2.0, one-time download link support for mobile applications has been introduced. Now every user who has been authorised to a particular mobile app (Android, IOS or webapp) can subscribe and generate one-time download link for mobile app binary.

    In App Manager, a user can download/install mobile app via WSO2 Mobile Device Manager (More information is available here or he can directly download the binary. One time download link support is provided for both installation types. But here, I would illustrate how to generate and retrieve sharable one-time download link for direct binary download.

    First, you need to obtain OAuth access token with 'appm:subscribe' scope (Please refer to App Manager documentation on OAuth access token generation). Then you need to get the application Id of the preferred mobile application that you need to download/install. For example, suppose we have an android mobile application in App Store, with appId '3cf028b6-ead6-49f4-a43f-84d384c00d5e'. Then use the obtained OAuth access token to generate a one-time download by accessing the app direct download REST API.

    REST API        : http://localhost:9763/api/appm/store/v1.1/apps/mobile/id/{appId}/download
    HTTP Method  : POST
    HTTP Headers : Authorization: Bearer {access_token}

    If you use CUrl as the REST client, below will be the one-time download link generation command.
    curl -X POST 
    -H "Authorization: Bearer 8cda473d-a40a-3ddb-b596-6eb967819ee0" 
    "http://localhost:9763/api/appm/store/v1.1/apps/mobile/id/3cf028b6-ead6-49f4-a43f-84d384c00d5e/download"
    

    When this particular API is accessed with authorised user access token,

    1. If the user subscription is not available, he will be subscribed to the mobile app
    2. App URL will be generated and returned with the response
    The following is a sample one-time download URL returned with the response.


    {
      "appUrl": "http://localhost:9763/api/appm/store/v1.1/apps/mobile/binaries/one-time/84855dc5-ddb6-4e8b-83e0-20f6c24d429b"
    }
    
    You can directly access the URL and download/install the app.

    Tuesday, June 21, 2016

    Audit Logs in WSO2 App Manager

    WSO2 App Manager provides Audit log support from the version 1.2.0. Audit logs provide you the information regarding the various user actions performed  against the server. In WSO2 App Manager 1.2.0, audit logs are provided for following user actions.

    App Publisher related audit logs

    • Login to app publisher
    • Creating a webapp
    • Updating a webapp
    • Changing the lifecycle state of a webapp
    • Deleting a webapp
    • Creating a new version of a webapp
    • Documentation create
    • Logout from App publisher

    App Store related audit logs

    • Login to app store 
    • Subscribing to a webapp
    • Unsubscribing to a webapp
    • Adding a webapp into Favourite app list
    • removing a webapp from Favourite app list
    • Rating/Commenting on webapp

    By default, audit logs  are not enabled  in App Manager. Please follow the steps given below to enable audit logs.
    1. Download WSO2 App Manager 1.2.0
    2. Extract the product into a folder. I will refer this folder as <APPM_HOME>
    3. Open <APPM_HOME>/repository/conf/log4j.properties file and append following audit log configurations into file.

    # Configure audit log for auditing purposes
    log4j.logger.AUDIT_LOG=INFO, AUDIT_LOGFILE
    log4j.appender.AUDIT_LOGFILE=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.AUDIT_LOGFILE.File=${carbon.home}/repository/logs/audit.log
    log4j.appender.AUDIT_LOGFILE.Append=true
    log4j.appender.AUDIT_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout
    log4j.appender.AUDIT_LOGFILE.layout.ConversionPattern=[%d] %P%5p - %x %m %n
    log4j.appender.AUDIT_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S]
    log4j.appender.AUDIT_LOGFILE.threshold=INFO
    log4j.additivity.AUDIT_LOG=false
    


    After completing above steps, restart the server. Then you will find the audit.log file created in  <APPM_HOME>/repository/logs/ folder. Once you have performed any of the user actions mentioned, relevant logs will be generated and persisted in audit.log file.

    For example, user signup, app create, update and delete actions will contain similar audit logs as follows.
    [2016-06-22 09:47:24,242]  INFO -  Initiator : admin@carbon.super | Action : Login | Target : ApplicationAuthenticationFramework | Data : { "ContextIdentifier" : "6003337f-ec87-4bbb-8ada-32a89ba1c99a","AuthenticatedUser" : "admin@carbon.super","AuthenticatedUserTenantDomain" : "carbon.super","ServiceProviderName" : "publisher","RequestType" : "samlsso","RelyingParty" : "publisher","AuthenticatedIdPs" : "eyJ0eXAiOiJKV1QiLCAiYWxnIjoibm9uZSJ9.eyJpc3MiOiJ3c28yIiwiZXhwIjoxNDY2NTY5MDQ0MjI4MzAwMCwiaWF0IjoxNDY2NTY5MDQ0MjI4LCJpZHBzIjpbeyJpZHAiOiJMT0NBTCIsImF1dGhlbnRpY2F0b3IiOiJCYXNpY0F1dGhlbnRpY2F0b3IifV19." } | Result : Success
    [2016-06-22 09:47:24,619]  INFO -  "Time" : "2016-06-22 09:47:24 +0530 ", "Action" : "User SignedIn ","TenantID" : "-1234","UserName" : "admin@carbon.super ", "Subject" : "", "SubjectID" : ""
    [2016-06-22 09:47:30,061]  INFO -  "Time" : "2016-06-22 09:47:30 +0530 ", "Action" : "NewPolicyCreated ","TenantID" : "-1234","UserName" : "admin@carbon.super ", "Subject" : "", "SubjectID" : ""
    [2016-06-22 09:48:00,371]  INFO -  "Time" : "2016-06-22 09:48:00 +0530 ", "Action" : "NewAssetAdded ","TenantID" : "-1234","UserName" : "admin@carbon.super ", "Subject" : "webapp", "SubjectID" : "{providerName='admin', apiName='travelApp', version='v1'}"
    [2016-06-22 09:48:00,580]  INFO -  Initiator : admin | Action : create | Target : 0 | Data : { travelApp-v1 } | Result : Success
    [2016-06-22 09:48:00,689]  INFO -  Initiator : admin | Action : update | Target : 21 | Data : { travelApp-v1 } | Result : Success
    [2016-06-22 09:49:37,522]  INFO -  "Time" : "2016-06-22 09:49:37 +0530 ", "Action" : "AssetUpdated ","TenantID" : "-1234","UserName" : "admin ", "Subject" : "webapp", "SubjectID" : "{providerName='admin', apiName='travelApp', version='v1'}"
    [2016-06-22 09:50:03,527]  INFO -  "Time" : "2016-06-22 09:50:03 +0530 ", "Action" : "AssetDeleted ","TenantID" : "-1234","UserName" : "admin@carbon.super ", "Subject" : "webapp", "SubjectID" : "{providerName='admin', apiName='travelApp', version='v1'}"
    


    Friday, June 1, 2012

    How to write a Web Service Client with Apache Axis2?


    In my previous post, I have illustrated how to write a simple web service with Apache Axis2 and how to deploy it. But how to invoke it?

    In this post, I'm going to describe how to invoke a web service using a web Service Client. For that we have to look at the WSDL file of the service we are going to invoke.
    What is WSDL?
    WSDL stands for Web Service Description Language. It is written in XML and it is to describe the web service and it specifies the location where the web service is located, available operations, parameters etc.
    To get the WSDL file, start the axis2server and go to the link http://localhost:8080/axis2/services/ . You may see the deployed services. Then just click on the service you are going to invoke. Then you'll be directed to the WSDL file of that service. We need to access the WSDL file when we are writing the Client code.
    There are so many ways to invoke a web service. In this tutorial, I'll describe 2 ways of them.

    1. Using WSDL2Java tool provided with axis2
    2. Using Eclipse IDE with tomcat server.
    In each method, by accessing the WSDL file, client stub is generated ( Client stub acts as the interface to web service and it can be considered as the client code). The communication between web service and the client is done by sending SOAP messages.
    Let's follow the first method.

    1) Using WSDL2Java tool provided with axis2

    In this procedure, we are going to use WSDL2Java tool to generate the client stubs, which was provided with axis2. For that go to axus2/bin/ folder. Then you will see wsdl2java.sh and wsdl2java.bat files.
    If you are using Linux, you have to use .sh file, and if you are using windows, you have to use .bat file.

     In Linux, give the following command to generate client stub.
    "sh wsdl2java.sh -uri <WSDL url> -o /path to the client code to be generated/ "

    In this case, I'm going to invoke 'CalcSumService', service and I have to give following command. Here, I'm going to generate my client code in  the location of /home/Development/client/temp.
    "sh wsdl2java.sh -uri http://localhost:8080/axis2/services/CalcSumService?wsdl -o /home/Development/client/temp"

    If you are using Windows, give following command.
    "wsdl2java.bat -uri <WSDL url> -o /path to the client code to be generated/ "

    In this case,
    "wsdl2java.bat-uri http://localhost:8080/axis2/services/CalcSumService?wsdl -o /home/Development/client/temp"

    Now go to the folder where you were specified in the above command to generate client code. In my case  /home/Development/client. You will see a build.xml file and src folder which contains the package org.apche.ws.axis2. This package CalcSumServiceCallbackHandler.java and CalcSumServiceStub.java class. Now we can see that client stub has generated. Next step is to write the client code.

    This is the method we are going to invoke in the web service.

    public int calcSum(int value1, int value 2){
    
             return value1+value2;
    
    }
    


    Let's write a class named 'CalcSumClient' to invoke the above method in web service.

    package org.apache.ws.axis2;
    import java.rmi.RemoteException;
    import org.apache.axis2.AxisFault;
    import org.apache.ws.axis2.CalcSumServiceStub.CalcSumResponse;
    
    public class CalcSumClient {
    
        public static void main(String[] args) throws RemoteException {        
    
            CalcSumServiceStub stub = null;
    
            try {
    
                stub = new CalcSumServiceStub();
    
            } catch (AxisFault e) {
    
                e.printStackTrace();
    
            }
    
            CalcSumServiceStub.CalcSum request= new CalcSumServiceStub.CalcSum();
    
            request.setValue1(1);
    
            request.setValue2(2);
    
            CalcSumResponse response= stub.calcSum(request);
    
            System.out.println(response.get_return());
    
           
    
        }
    
    }
    




    The  above code would invoke the web service. First we have to create a CalcSumServiceStub object. CalcSumServiceStub class contains an inner class called 'CalcSum'. Basically, for each operation in the web service, an inner class from that name of the operation in contained in the stub class. In this case, the operation  in the web service we are going to invoke ic 'calcSum'. Thus we have to create an object called request from CalcSum inner class.


          CalcSumServiceStub.CalcSum request= new CalcSumServiceStub.CalcSum();

    Next  we have to set input values for the invoking operation. In this case we have to set value1 and value2 of the 'request' object.

      request.setValue1(1);
      request.setValue2(2);   

    Then we have to pass the request object to stub.calcSum method and that method will return CalcSumResponse object.

    The returning object is contained with the result coming from the web service.

    Now our client code is ready. Then put the above java class into the same package where the stub and the callbackhandler is located. Then go inside the src folder, where the org.apache.ws.axis2 package is located. Then we can compile the code giveng following command.

    javac -extdirs /path to axis2 /lib/ <package name> *.java

    In this case give,

    "javac -extdirs /home/axis2/lib  org/apache/ws/axis2/*.java"


    Then the java classes are compiled. Next step is to run the client code. For that enter,

    "java -Djava.ext.dirs=/Path to axis2/lib/ <packagename.Client Class name>"

    In this case you have to give,

    "java -Djava.ext.dirs=/home/axis/lib org.apache.ws.axis2.CalcSumClient"

    If it is correctly compiled and run, the calculated value will be displayed in the console as '3'.

    Wednesday, May 30, 2012

    How To Write a Web service with Apache Axis2 ?

    Basically,a web service is a web based application. It is a way of integrating various applications which are web based using SOAP, XML and WSDL.
    In my android application, I have used a web service as a server application. I have created a web service with Apache axis2, which provides details of nearest hospitals and police stations with respect to current location provided  by the client application.

    In this article, I would illustrate how to write a simple web service using Apache Axis2. First you have to download Apache axis2 binary distribution and install it. (Check whether you have installed java by giving 'java version' command before starting everything. If not download jdk and install java using installation guide provided with downloaded version.)

    Let's write a simple web service to calculate the sum of two numbers. 'CalcSumService' is our web service and its simply a java class which has a method to calculate the sum of given two values.
    public class CalcSumService {
    
        public int calcSum(int value1,int value2){
            return value1+value2;
        }
    }
    


    Then save the class as 'CalcSumService.java' and compile (using 'javac CalcSumService.jav '). Then 'CalcSumService.class' would be generated.
    To host an web service in Apache axis2, we have to create a services.xml file to inform the Axis2 about the newly deploying service. The services.xml file should be contained the following code.

    <service name="CalcSumService" >
       <description>This is the HelloWorld service</description>
       <parameter name="ServiceClass">HelloWorld</parameter>
       <operation name="sayHello">
          <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
       </operation>
    </service>
    
    




    Now, all the elements need to host the web service are ready. First create a folder name META-INF and copy the 'services.xml' file into that folder. Then create a zip folder containing that META-INF directory and compiles CalcSumService.class. Rename that zip file as 'CalcSumService.aar'.

    Otherwise, locate 'META-INF' and 'CalcSumService.class' in a directory called 'temp'. Then go inside that directory and execute 'jar -cvf CalcSumService.aar*'. Then the .aar file would be generated.

    After successfully creating CalcSumService.aar file, go to axis2/repository/services directory and copy the  'CalcSumService.aar'  file in to services directory.
    Now our service is hosted. If we want to check whether the serviceis successfully hosted, we have to start the SimpleHTTPServer. For that go to axis2/bin and start the axis2server.
    In Linux, give 'sh axis2server.sh' and in windows give 'axis2server.bat drive:/path to bin/' to run the server. Then in your web browser, enter the url ' http://localhost:8080/axis2/services/'. Then the deployed service would be visible for you. You can see the WSDL file of the hosted service by clicking the service name.
    If the service is successfully deployed, you might see the service as shown below with service name and functions available.



    Using Eclipse IDE

    We can use Eclipse IDE to host a web service. That is more easier than the above described procedure. Let's see how to write a simple web service and how to host it using axis2.  First download Apache Axis2 Binary Distribution  and Eclipse IDE for  java EE developers . Then install Eclipse.

    After installing Eclipse, open it. Now we have  to set Axis2 Runtime. For that goto Windows> Preferenece and select  'web services' from  drop down menu in the left side.


    Then select Axis2 Preference from the drop down list. You will find the below like dialog box.


    In that dialog box, under Axis2 Runtime, browse the location where your downloaded Axis2 folder is located. Then click ok. Now we have successfully set the Axis2 Runtime. Now we have to define a server to deploy the web service. Here I use Tomcat server to host the web service.
    In Eclipse select File>New>Other... Then select the Servers from the drop down menu.

    Then select Server. Then the below window will pop out to select a server.


    Then the preferred server has to be selected. In my case I select Tomcat version 7, and click next. Then you'll find the below window to install Tomcat server which you have selected.

    If you have downloaded Tomcat Server, just give the location where you have located it, using Browse. Otherwise Click on Download and install to install the requested Tomcat Server.

    Our next step is to start a 'Dynamic web project' and implement our web service class. For that goto File>New>Other>Web>Dynamic Web Project as shown in the image below.

    Click 'Next' and you will find the below window.


    There, give a name for the Dynamic Web project and in Configuration. Then click finish.
    Now your project will look like this.

    Now right click on Java Resources > src . Go to Nev>class. Then create a java class name CalcSumService.java as in the diagram shown below. Give a package name also.



    Now in the created java class, write a method called calcsum to calculate the sum of two given integers.



    public class CalcSumService {
    
        public int calcSum(int value1,int value2){
            return value1+value2;
        }
    }
    
    
    Now our java class is ready. What we have to do next is to create the web service using that java class. For that , right click on the CalcSumService.java  and select web services>create web services. Then you will find the following window. 

    In that window, you have to select Server runtime and web service runtime in Configuration. In server runtime, select the Tomcat v7.0 server, and in web service runtime, select Apache axis2

    Then click ok and after successfully setting configuration, click finish.

    Then 'Next'
    'Start Server'


    Then go to the URL : http://localhost:8080/CalcSumService/services/listServices . If the service is successfully deployed, you would find following page shown below and the CalcSumService would be visible to you.

    Friday, February 24, 2012

    About - Emergency Aid



    login form
    Emergency aid, nearest hospital and police station detecting app, allow users to register for the system and help in to populate the details of available hospital locations etc. The below image shows the user interface of the android application.
    When the user wants the app to track the nearest hospitals and police station, the application itself  views the map and locations are indicated by icons. The below view shows how the locations are indicated in the map in order to make it convenient for the user to figure out.

    Satellite view 
    Traffic view 
    The user can login to the system and add current GPS location to central data base. Then the data will be delivered to web service as SOAP messages and will be added to data base after administrator confirmation. The user interface allowed to add location detals are shown below.

    Then the confirmation messages will be shown and according to user reactions, the data will be transferred to the webservice.



    Emergency Aid

    Emergency Aid-Android Application to detect Nearest Hospitals and Police Stations

    Emergency aid is an android application developed by myself to detect the nearest hospitals and police stations and direct you in the shortest path available. In an emergency situation like a road accident, a fire, a natural disaster, a crime etc, it is difficult to find the nearest hospital and the nearest police station if we are not aware of area of the current place. Thus I thought of developing a mobile application for android platform as a solution for that.

    The locations of the nearest hospitals and police stations locations are found by accessing the web service and the current location is detected by GPS. Then the nearest hospital and police station locations are found with respect to current location.


    This application helps users to find nearest locations of hospitals and police stations, call them and request available services, view the locations in Google map,  get addresses and direction guide.

    I have used 'Eclipse-Indigo' as my development IDE and Android SDK with ADT plugin for my application implementations. The web service is hosted by using Apache Axis2, in Tomcat server. In upcoming posts, I hope to illustrate in details what are the steps I have followed in developing this mobile app.

    Whitelisting and Blacklisting IPs for APIs in API Manager

    Most of the time we come across different scenarios where we need to, Whitelist an IP for an API (Limiting API access for a given IP only)...