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

Saturday, July 30, 2016

Securing WSO2 ESB proxies with Kerberos - part 2 (Active directory (AD) as the KDC)

In a previous post, we looked at how to secure a WSO2 ESB proxy services using kerberos in which  Key Distribution Center (KDC) is the WSO2 identity server. In this post we'll look at securing WSO2 ESB proxy services when the KDC is the Active Directory (AD).

When the Key Distribution Center (KDC) is the Active Directory (AD), the SPN is usually attached with a service account. Contact your Windows Administrators to create an SPN and a service account and generate a key tab file against that. The main difference from WSO2 IS and AD based KDC is that, in AD the SPN doesn’t provide a text password, rather it’s in the keyTab file.

To create an SPN for a related service account, use the following command.
setspn -s HTTP/USESB.your.domain.com us\us-wso2esb
setspn -s HTTP/USESB us\us-wso2esb
Change the SPN and service account accordingly.

Ask the administrators to create the keytab using the following command.
ktpass /out wso2.keytab /princ HTTP/USESB@YOUR.DOMAIN.COM /mapuser us\us-wso2esb /pass password /crypto All /ptype KRB5_NT_PRINCIPAL

This will create a keyTab file named wso2.keytab

Get the keytab file and place it in a location accessible by the WSO2 ESB.

In our case the KDC hostname is us.your.domain.com. The ESB configuration is same as like the previous case. But make the following changes in the krb5.conf

[libdefaults]

        default_realm = US.YOUR.DOMAIN.COM
        default_tgs_enctypes = rc4-hmac des-cbc-crc des-cbc-md5 aes256-sha1 aes128-aha1
        default_tkt_enctypes = rc4-hmac des-cbc-crc des-cbc-md5 aes256-sha1 aes128-aha1
        permitted_enctypes = rc4-hmac des-cbc-crc des-cbc-md5 aes256-sha1 aes128-aha1
        allow_weak_crypto = true 

[realms]
                US.YOUR.DOMAIN.COM = {
                        kdc = us.your.domain.com
                        default_domain = US.YOUR.DOMAIN.COM
}

[domain_realm]
        .us.YOUR.DOMAIN.COM = US.YOUR.DOMAIN.COM
        us.YOUR.DOMAIN.COM = US.YOUR.DOMAIN.COM

[login]
        krb4_convert = true
        krb4_get_tickets = false
Have the jaas.conf contents be like the below.
Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
storeKey=true
useTicketCache=false
isInitiator=false
keyTab="/carbon/wso2/esb/keytab/wso2.keytab"
principal="HTTP/USESB@US.YOUR.DOMAIN.COM";
};
Note the useKeyTab and the keyTab property, which is different from the WSO2 IS as a KDC scenario. Provide the path of the keyTab file location to the keyTab parameter.

Next when you secure the proxy, you have to provide the SPN name as the AD configured SPN. In our case the SPN is HTTP/USESB@US.YOUR.DOMAIN.COM

Also note since you have no password for the SPN, you can provide the service account password which was created at the AD end. In fact that won’t be used in this case, since the password will get resolved from the keyTab file. Once the proxy is secured, we need to do one more change for Java 7. Go to the proxy dashboard and click Policies. In both, Binding echoSoap11Binding and Binding echoSoap12Binding policies add the following line below the service principal name.
<rampart:property name="kdc.ticket.decoder">org.wso2.carbon.krb.Java7.TicketDecoder</rampart:property>

This is required to be added due to a bug that was identified in the implementation and require a patch from WSO2. If you are a support customer of WSO2, you may open a support ticket to request the patch WSO2-CARBON-PATCH-4.2.0-1811.
If you are not a support customer, you can run the ESB using JRE 1.6.

That’s it in ESB end.

When you start the server, start the ESB with the following system property,

./wso2server.sh -Djava.security.krb5.conf= /carbon/wso2/esb/wso2esb-4.8.1/repository/resources/security/krb5.conf start

You may insert that property in the wso2server.sh file as well.

Now you can try invoking the echo proxy using soap ui and it should fail saying “security header does not found”. This is because the request didn’t contain any security information, such as the kerberos ticket etc. In fact it’s difficult to create a soap ui project to work with kerberos, as the WS-Security spec demands a format for the soap request, such as signing the message payload from kerberos ticket and so on.

We have written a java client to cater this. Clients need to incorporate same mechanism to call a kerberos secured proxy. Please find the Java client here.

Note: however the Java client should be running in a machine where it can connect to the AD based KDC.

Testing with a Java client

Change the krb5.conf of the java client as the following in the java client.
[libdefaults]
        default_realm = US.YOUR.DOMAIN.COM
        default_tgs_enctypes = rc4-hmac
        default_tkt_enctypes = rc4-hmac
        permitted_enctypes = rc4-hmac
        allow_weak_crypto = true

[realms]
      US.YOUR.DOMAIN.COM = {
         kdc = us.your.domain.com
}
Note the KDC ip address. Change accordingly. Also change the config.properties to match the windows server.
keyStorePath=C:\\Users\\smohamednazeer\\Desktop\\DevKeyTab\\wso2carbon.jks
keyStorePassword=wso2carbon
axis2ClientPath=C:\\Users\\smohamednazeer\\Documents\\codes\\kerberospocsolution\\kerberosJavaClient\\repo\\conf\\client.axis2.xml
policyFilePath=C:\\Users\\smohamednazeer\\Documents\\codes\\kerberospocsolution\\kerberosJavaClient\\repo\\conf\\policy.xml
serviceEndpoint=https://<ip-address or domain name>:9443/services/echo
If you are using a custom keystore, use that keystore path and password instead.

The rampart configuration of policy should be changed. Client principal name in this case would be the logged in user. In our case we have the following configurations.
<rampart:RampartConfig xmlns:rampart="http://ws.apache.org/rampart/policy">

  <rampart:timestampPrecisionInMilliseconds>true</rampart:timestampPrecisionInMilliseconds>
  <rampart:timestampTTL>300</rampart:timestampTTL>
  <rampart:timestampMaxSkew>300</rampart:timestampMaxSkew>
  <rampart:timestampStrict>false</rampart:timestampStrict>
  <rampart:nonceLifeTime>300</rampart:nonceLifeTime>

  <rampart:kerberosConfig>
    <rampart:property name="client.principal.name">smohamednazeer@US.YOUR.DOMAIN.COM</rampart:property    <rampart:property name="client.principal.password">xxxxxxxxxxxx</rampart:property>
    <rampart:property name="service.principal.name">HTTP/USESB@US.YOUR.DOMAIN.COM</rampart:property>
    <rampart:property name="java.security.krb5.conf">C:\Users\smohamednazeer\Documents\codes\kerberospocsolution\kerberosJavaClient\repo\conf\krb5.conf</rampart:property>
    <rampart:property name="java.security.auth.login.config">C:\Users\smohamednazeer\Documents\codes\kerberospocsolution\kerberosJavaClient\repo\conf\jaas.conf</rampart:property>
    <rampart:property name="javax.security.auth.useSubjectCredsOnly">true</rampart:property>
    <rampart:property name="kdc.ticket.decoder">org.wso2.carbon.krb.Java7.TicketDecoder</rampart:property>
  </rampart:kerberosConfig>

</rampart:RampartConfig>
Enter the username you use to login to Windows machine as the client.principal.name, or you have to enter a username that exists in your AD. Enter the password that you use to login to the Windows machine for the client.principal.password, or enter the password of the respective AD user.

Note the Java7.TicketDecoder property, if you are running the ESB in Java 7 (Note: To use with Java 7, you'll need to have above mentioned patch applied in the ESB 4.8.1 and ESB 4.9.0) If you are running in Java 6, you may remove that line.

If your server is using a custom keystore (which is normally the case), following needs to be done.

1.  Use the same keystore, its alias and password of primary keystore for RegistryKeyStore. This is due to a known issue in the system (see [1]). This will get fixed in the future releases.

[1] https://wso2.org/jira/browse/CARBON-15786

2.  Change the config.property of the Java client to use the new keystore and the password

To build this project you have to point the project to the plugins directory of the WSO2 ESB 4.8.1. You may copy the plugins directory somewhere else and point the project to that and build. If you are running the server in Java 7, make sure the plugins directory also contain the patched jars of the above mentioned issue; wss4j, rampart and TicketDecoder.

Now if you run the client you should see the response of the echo service. You should see an output like the following in the console.
Calling service with parameter - Hello Shazni!!!!!!!

Request = <p:echoString xmlns:p="http://echo.services.core.carbon.wso2.org"><in>Hello Shazni!!!!!!!</in></p:echoString>

The response is : <ns:echoStringResponse xmlns:ns="http://echo.services.core.carbon.wso2.org"><return>Hello Shazni!!!!!!!</return></ns:echoStringResponse>

Testing with a Windows Communication Foundation (WCF) client

The WCF client used to test the echo proxy is located here.

The WCF client creates a form with a button, when clicked it calls the echo proxy. Open App.Config in the Visual Studio.
      <endpoint address="http://<ip address or domain name>:8280/services/echo" behaviorConfiguration=""
        binding="customBinding" bindingConfiguration="customTextMessageEncoding"
        contract="WSO2.Echo.echoPortType">
        <identity>
          <servicePrincipalName value="HTTP/USESB@US.YOUR.DOMAIN.COM" />
        </identity>
      </endpoint> 
Note the endpoint address and the servicePrincipalName.

The client executable is located in EchoWcfClientServiceVisualStudio\EchoClient\bin\Debug

If the executable is not found, you’ll have to build the project in Visual Studio.

Either run the executable or run the client within Visual Studio. This should bring up a form. Click the echo button. The response should be shown in the message box.

You might have noticed that we used the http address. If you want to use the https endpoint for SSL, you have to add the following element in the app.config.
<httpsTransport authenticationScheme="Anonymous" bypassProxyOnLocal="false"
           hostNameComparisonMode="StrongWildcard" proxyAuthenticationScheme="Anonymous"
           realm="" useDefaultWebProxy="true" />
instead of the following http binding,
<httpTransport authenticationScheme="Anonymous" bypassProxyOnLocal="false" 
hostNameComparisonMode="StrongWildcard" proxyAuthenticationScheme="Anonymous" 
realm="" useDefaultWebProxy="true" />
And when you run the WCF client in the Windows machine, you would get an SSL error if you haven’t imported the ESB servers' primary keystore’s certificate to the Windows trusted certificates. Assuming you have generated your keystores and exported the certificate out of it, follow the steps here to import the certificate file to the Windows server.

Once the certificates are imported, you should be able to call the proxy with the https endpoint.

Saturday, July 23, 2016

Securing WSO2 ESB proxies with Kerberos - part 1 (WSO2 Identity Server as a KDC)

WSO2 Enterprise Service Bus proxies can be secured in various security mechanisms. There are around 20 out of the box security schemes that we can use to secure proxies. Kerberos is one of them. In this post and next we go through the setup and configuration of the Kerberos with two options.
  • WSO2 Identity Server (IS) as Key Distribution Center (KDC)
  • Active directory (AD) as the KDC
In this post we shall look into the first option and see how we can invoke a secured proxy using a Java client. This post is a supplementary to some awesome posts that WSO2 folks have written in the past. Notable posts are the [1], [2] and [3]. I wanted to write this post to show the steps in the latest (or recent) versions of the products. Some configurations and locations have been changed and I encountered few issues setting this up. So I wanted to compile them up in one location. Hope this would be helpful for anyone wanting to know how to use Kerberos security with WSO2 Enterprise Service Bus (ESB) for proxies, hence for SOAP calls. In the next post I'll show you how to use a Java and a .Net [Windows Communication Foundation (WCF) ] client to invoke a secured proxy.

I would like to thank Prabath for permitting me to copy and modify some of the code he used to demonstrate in his posts.

WSO2 Identity Server (IS) as the Key Distribution Center (KDC)

In this procedure we need to have WSO2 IS and WSO2 ESB setup in two server machines. (You may try this with the same server with two different port offsets for WSO2 IS and WSO2 ESB). It’s assumed that you have configured the two servers beyond this point. Look at ESB and IS documentation for reference at [4] and [5]. WSO2 IS can be used in a standalone mode (without any external database setup) for you to work on this.

In WSO2 IS (here we used IS version 5.0.0), let’s setup the KDC.

First we have to enable the KDC. Open embedded-ldap.xml and enable KDC as below.
  <KDCServer>
    <Property name="name">defaultKDC</Property>
    <Property name="enabled">true</Property>
    <Property name="protocol">UDP</Property>
    <Property name="host">localhost</Property>
    <Property name="port">${Ports.EmbeddedLDAP.KDCServerPort}</Property>
    <Property name="maximumTicketLifeTime">8640000</Property>
    <Property name="maximumRenewableLifeTime">604800000</Property>
    <Property name="preAuthenticationTimeStampEnabled">false</Property>
  </KDCServer> 
If you want to change the default realm of the KDC, change the “realm” property. By default it’s WSO2.ORG. We’ll keep it as it’s in this case for simplicity.
<Property name="realm">WSO2.ORG</Property>
We can also enable the KDC setting in the user-mgt.xml. Enable the following property in the UserStoreManager.
<Property name="kdcEnabled">true</Property>

Create a file named jaas.conf with following contents and place inside <IS_HOME>/repository/conf/security directory.

Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=false
storeKey=true
useTicketCache=false
isInitiator=false;
};

Client {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=false;
};

Create a file name krb5.conf with following contents and place it in <IS_HOME>/repository/conf/security directory. This says your KDC locates in the current machine.

[libdefaults]
        default_realm = WSO2.ORG
        default_tkt_enctypes = rc4-hmac des-cbc-md5
        default_tgs_enctypes = rc4-hmac des-cbc-md5
        dns_lookup_kdc = true
        dns_lookup_realm = false

[realms]
        WSO2.ORG = {
            kdc = 127.0.0.1
   }

Now let’s start the WSO2 IS Server.

Once started the server, we have to create a Service Principal (SPN) and a client principal to use with kerberos ticket granting system (TGS). Once the server is started, navigate to Configure -> Kerberos KDC -> Service Principals and click “Add new Service Principal”. Provide a service principal name, description and a password. In this case we used the following service principal name.

SPN Name : esb/localhost@WSO2.ORG

Now create a new user by navigating to Configure -> Users and Roles -> Users -> Add User.

In our case I have added a user name “test” with a password. This will be the client principal.

That’s all with WSO2 IS KDC configuration.

Let’s now configure security in a sample proxy in WSO2 ESB (We used WSO2 ESB 4.8.1). In my case I’ve secured the default echo proxy. You may do the same for any other proxy.

Configuring ESB for kerberos.

Add the following into jass.conf file and place it in <ESB_HOME>/repository/conf/security directory. Note the principal name configuration

Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=false
storeKey=true
useTicketCache=true
isInitiator=false
principal="esb/localhost@WSO2.ORG";
};
Add the following to the krb5.conf and place it in in <ESB_HOME>/repository/conf/security directory. Configure the ip address of the WSO2 IS in kdc section. If the WSO2 IS is running in the same server as WSO2 ESB, this is the loop back address 127.0.0.1, which is the case in my scenario. Remember to use all caps for the default_realm.

[libdefaults]
        default_realm = WSO2.ORG
        default_tgs_enctypes = des-cbc-md5
        default_tkt_enctypes = des-cbc-md5
        permitted_enctypes = des-cbc-md5
        allow_weak_crypto = true

[realms]
        WSO2.ORG = {
                kdc = 127.0.0.1:8000
        }

[domain_realm]
        .wso2.ORG = WSO2.ORG
        wso2.ORG = WSO2.ORG

[login]
        krb4_convert = true
        krb4_get_tickets = false



  • Start the ESB server and navigate to the proxy list.
  • Click the echo proxy to navigate into the dashboard
  • Click the security button
  • Select ‘yes’ in the security section
  • Select the kerberos security mechanism (Item number 16) and click next
  • Provide the SPN name you configured in the WSO2 IS together with its password and click Finish


  • Now you can try invoking the echo proxy using soap ui and it should fail saying “security header does not found”. This is because the request didn’t contain any security information, such as the kerberos ticket etc. In fact it’s difficult to create a soap ui project to work with kerberos, as the specification requires a format for the soap request, such as signing the message payload from kerberos ticket, having a time stamp and so on.

    We have written a java client to cater this (Thanks Prabath, once again for permitting me to use and modify your client). Clients need to incorporate same mechanism to call a kerberos secured proxy in the Java code. Please find the client here. We shall discuss about a .Net client in the next post.

    Open this project in IntelliJIDEA or your favorite IDE.

    Navigate to the config.properties and configure the keyStorePath, keyStorePassword, axis2ClientPath, policyFilePath and servicEndpoint according to your setup. We are using the default keystore in this setup and the configuration is like the following.

    # Kerberos configs
    keyStorePath=/home/shazni/ProjectFiles/kerberosJavaClient/repo/resources/wso2carbon.jks
    keyStorePassword=wso2carbon
    axis2ClientPath=/home/shazni/ProjectFiles/kerberosJavaClient/repo/conf/client.axis2.xml
    policyFilePath=/home/shazni/ProjectFiles/kerberosJavaClient/repo/conf/policy.xml
    serviceEndpoint=https://localhost:9448/services/KerberosTestReg
    
    
    Note my ESB run on port offset of 5 hence the port 9448.

    Next, open up the policy.xml file and make the rampart configuration changes for client.principal.name, client.principal.password (This should be the user you created in the WSO2 IS), service.principal.name, java.security.krb5.conf, java.security.auth.login.config and javax.security.auth.useSubjectCredsOnly. In my case it’s like the following.

    <rampart:RampartConfig xmlns:rampart="http://ws.apache.org/rampart/policy">        
    
          <rampart:timestampPrecisionInMilliseconds>true</rampart:timestampPrecisionInMilliseconds>
          <rampart:timestampTTL>300</rampart:timestampTTL>
          <rampart:timestampMaxSkew>300</rampart:timestampMaxSkew>
          <rampart:timestampStrict>false</rampart:timestampStrict>
          <rampart:nonceLifeTime>300</rampart:nonceLifeTime>
    
          <rampart:kerberosConfig>
               <rampart:property name="client.principal.name">test_carbon.super</rampart:property>
               <rampart:property name="client.principal.password">test123</rampart:property>
               <rampart:property name="service.principal.name">esb/localhost@WSO2.ORG</rampart:property>
               <rampart:property name="java.security.krb5.conf">repo/conf/krb5.conf</rampart:property>
               <rampart:property name="java.security.auth.login.config">repo/conf/jaas.conf</rampart:property>
               <rampart:property name="javax.security.auth.useSubjectCredsOnly">true</rampart:property>
          </rampart:kerberosConfig>
    
        </rampart:RampartConfig>
    

    Also open up the krb5.conf file located in the client code and configure your kdc ip address. In this case the ip address of the WSO2 IS server.

    Now if you run the client you should see the response of the echo service. You should see an output like the following in the console.

    Calling service with parameter - Hello Shazni!!!!!!!
    Request = <p:echoString xmlns:p="http://echo.services.core.carbon.wso2.org"><in>Hello Shazni!!!!!!!</in></p:echoString>
    The response is : <ns:echoStringResponse xmlns:ns="http://echo.services.core.carbon.wso2.org"><return>Hello Shazni!!!!!
    

    This client contacts the WSO2 IS KDC to get a kerberos ticket and then uses the rampart library to build the request as compliant to the WS-Security specification and send the request to the proxy. At the ESB server end, the rampart resolves the request and wss4j validates the ticket by decryption and validating the signature of the request payload and call the backend service, if those validation passes. Subsequently gets the response and sign it back with the kerberos key and send the response back, once again in compliance with the WS-Security.

    That's all the configurations you got to do. This is a very simple example on how to use keberos security scheme in WSO2 ESB with WSO2 IS.

    In the next post I'll show how to configure the ESB with AD based KDC (specifically with a keyTab file, instead of using the SPN and it's password as used in this post)

    [1] http://wso2.com/library/articles/2012/07/kerberos-authentication-using-wso2-products/
    [2] http://blog.facilelogin.com/2010/12/kerberos-authentication-with-wso2-esb.html
    [3] https://malalanayake.wordpress.com/2012/12/13/how-to-invoke-the-echo-service-secured-by-kerberos-in-wso2-esb/
    [4] https://docs.wso2.com/display/ESB490/WSO2+Enterprise+Service+Bus+Documentation
    [5] https://docs.wso2.com/display/IS510/WSO2+Identity+Server+Documentation

    Thursday, February 18, 2016

    WSO2 Microservices Framework for Java (MSF4J) 1.0.0 is released

    WSO2 is pleased to announce that it has released the very first version 1.0.0 of the WSO2 Microservices Framework for Java (MSF4J). You can get more details from the following location.

    [1] http://wso2.com/products/microservices-framework-for-java/

    It gives you a lightweight fast runtime together with an annotation based programming model to create your micro services. Browse the following location for a quick start guide.

    [2] https://docs.wso2.com/display/MSF4J100/Quick+Start+Guide

    Enjoy creating your microservices!!!

    Tuesday, October 28, 2014

    Creating Roles and Assigning Permissions in WSO2 IS

    In this article I will try to explain the ways to create and assign roles in WSO2 Identity Server. I'll walk you through on creating and assigning roles in the Management console UI and then outline the ways to do the same using an API and using a Java client programmatically.

    Let's start the WSO2 Identity Server (IS) first. To download and run the WSO2 IS, look here.

    Once started login to management console. First let's look at how we can create a role named 'TestRole' and assign some permissions in the permission tree to it. This involves only a very few steps. Navigate to Configure -> Users and Roles -> Roles ->  Add New Role. Enter the role name as 'TestRole' and click next. The permission tree would be shown and you need to select the the relevant permission in the tree for this role. If you need to assign certain existing users to this role, click next and select those users. Otherwise click finish. That's it. You have successfully create a a new role named 'TestRole' and assigned permission for that. You can see the existing roles by navigating to Home -> Configure -> Users and Roles -> Roles. At this place you can view the permission, delete the role, assign user and also rename the role.

    Next we shall see how to create roles and assign any permission in the permission tree to those roles using a programmatic way, without using the UI. You can do that by calling an admin service as an API or using a Java client. I'll outline both the methods here.

    There is a web service API called RemoteUserStoreManagerService that can be used to manage users and roles. This is an Admin Service in the WSO2 carbon platform. Admin services in the WSO2 products are hidden by default. To see the wsdl of this web service you need to unhide the Admin service WSDLs. To do that, first, open up CARBON_HOME/repository/conf/carbon.xml and look for the following line.
    <HideAdminServiceWSDLs>true</HideAdminServiceWSDLs>
    Make it to 'false' and restart the server.

    After the server is successfully started, you can access the wsdl of the RemoteUserStoreManagerService by navigating to https://localhost:9443/services/RemoteUserStoreManagerService?wsdl (Replace 'localhost' part as applicable).

    Following are the two methods I mentioned

    1. You can create a SOAP UI project with this wsdl. You can use the addRole method to add the role. A sample SOAP call is given below to add a role named 'ValidRole' and assign permission under '/permission/admin/login/EmailLogin' where 'EmailLogin' being a new permission I created under '/permission/admin/login/'
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.ws.um.carbon.wso2.org" xmlns:xsd="http://dao.service.ws.um.carbon.wso2.org/xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <ser:addRole>
             <ser:roleName>ValidRole</ser:roleName>
             <ser:permissions>
                <xsd:action>ui.execute</xsd:action>
                <xsd:resourceId>/permission/admin/login/EmailLogin</xsd:resourceId>
             </ser:permissions>
          </ser:addRole>
       </soapenv:Body>
    </soapenv:Envelope>
    
    2. You can write a Java client instead and invoke the methods in the RemoteUserStoreManagerService. A sample Java program is shown below to achieve this. The very self explanatory. Note: you need to add the plugins directory of a IS product to the classpath of the program to build and run this.
    import org.apache.axis2.client.Options;
    import org.apache.axis2.client.ServiceClient;
    import org.apache.axis2.context.ConfigurationContext;
    import org.apache.axis2.context.ConfigurationContextFactory;
    import org.apache.axis2.transport.http.HTTPConstants;
    import org.apache.axis2.transport.http.HttpTransportProperties;
    import org.wso2.carbon.CarbonConstants;
    import org.wso2.carbon.um.ws.api.stub.PermissionDTO;
    import org.wso2.carbon.um.ws.api.stub.RemoteUserStoreManagerServiceStub;
    
    public class ISClient {
    
        private static final String CARBON_HOME = "/home/shazni/Downloads/WSO2/wso2is-5.0.0";
        private static final String SEVER_URL = "https://localhost:9443/services/";
        private static final String USER_NAME = "admin";
        private static final String PASSWORD = "admin";
        private static final String ROLE_NAME = "permissionRole";
    
        public static void main(String args[]){
    
            String trustStore = CARBON_HOME + "/repository/resources/security/wso2carbon.jks";
            System.setProperty("javax.net.ssl.trustStore",  trustStore );
            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
    
            ConfigurationContext configContext;
    
            try {
                configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem( null, null);
                String serviceEndPoint = SEVER_URL + "RemoteUserStoreManagerService";
    
                RemoteUserStoreManagerServiceStub adminStub = new RemoteUserStoreManagerServiceStub(configContext, serviceEndPoint);
                ServiceClient client = adminStub._getServiceClient();
                Options option = client.getOptions();
    
                option.setProperty(HTTPConstants.COOKIE_STRING, null);
    
                HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
                auth.setUsername(USER_NAME);
                auth.setPassword(PASSWORD);
                auth.setPreemptiveAuthentication(true);
                option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
                option.setManageSession(true);
    
                boolean  authenticate = false;
    
                try{
                    authenticate = adminStub.authenticate(USER_NAME, PASSWORD);
                } catch (Exception e){
                    e.printStackTrace();
                }
    
                if(authenticate){
                    System.out.println("User is authenticated successfully");
                } else {
                    System.err.println("User is authentication failed");
                }
    
                try{
                    PermissionDTO permissionDTO = new PermissionDTO();
                    permissionDTO.setAction(CarbonConstants.UI_PERMISSION_ACTION);
                    permissionDTO.setResourceId("/permission/admin/login/WebLogin");
    
                    PermissionDTO[] permissionDTOs = new PermissionDTO[1];
                    permissionDTOs[0] = permissionDTO ;
    
                    adminStub.addRole(ROLE_NAME, null, permissionDTOs);
                    System.out.println("Role is created successfully");
                } catch (Exception e){
                    System.err.println("Role creation is failed");
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    Well that's it. Hope this article has been informative to you.

    Friday, October 17, 2014

    Adding new permissions to permission tree in WSO2 Identity Server programmatically

    Let's start the WSO2 Identity Server (IS) first. To download and run the WSO2 IS, look here.

    The permission tree in WSO2 identity Server is simply,  a few collections stored in the underlying registry. Therefore adding new permissions to the permission tree involves adding a meaningful collection underneath a needed permission (collection). All these resources are stored in the registry path; /_system/governance/permission/admin. You can view this permission tree by navigating to an existing roles permission. To do that, navigate to Configure -> Users and Roles -> Roles -> Internal/everyone (Permissions) in the WSO2 IS. In this article I'm gonna write a sample Registry Client to add collections under /_system/governance/permission/admin to add new permissions to the permission tree. There's a permission named /_system/governance/permission/admin/login. We are going to add a permission named WebLogin under this. What needs to happen is simply creating a collection under this collection and assign a property called 'name' with its value being the name that needs to get displayed in the permission tree. This can be easily done using the management console of the WSO2 IS. What if someone needs to do this programmatically? Read further down to see how to!!

    Adding a resource or collection under another collection in a product like WSO2 IS involves few works. We can obtain some registry based services from a service client named WSRegistryServiceClient. Retrieving this service and performing operations like get and put on top of Registry instance is the easiest way to manipulate the resources in the registry tree. But this service feature is not shipped with some of the WSO2 products including WSO2 IS by default. Therefore it's required to add this feature to WSO2 IS. Following URL explains how to add a feature to any WSO2 product.

    https://docs.wso2.com/display/Carbon420/Installing+Features+via+the+UI

    Look for WS API feature under the category of Governance Registry section. Once installed you can use the Registry API's to add collections under the above collection /_system/governance/permission/admin.

    Following sample client java program adds the said collection.
    import org.apache.axis2.context.ConfigurationContext;
    import org.apache.axis2.context.ConfigurationContextFactory;
    import org.wso2.carbon.registry.core.Collection;
    import org.wso2.carbon.registry.core.Registry;
    import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
    
    import java.io.File;
    
    public class RegistryClient {
        private static final String CARBON_HOME = "/home/shazni/Downloads/WSO2/wso2is-5.0.0";
        private static final String axis2Repo = CARBON_HOME + File.separator + "repository" + File.separator + "deployment" + File.separator + "client";
        private static final String axis2Conf = CARBON_HOME + "/repository/conf/axis2/axis2_client.xml";
        private static final String username = "admin";
        private static final String password = "admin";
        private static final String serverURL = "https://localhost:9443/services/";
    
        private static WSRegistryServiceClient initialize() throws Exception {
            System.setProperty("javax.net.ssl.trustStore", CARBON_HOME + File.separator + "repository" +
                    File.separator + "resources" + File.separator + "security" + File.separator +
                    "wso2carbon.jks");
            System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
            System.setProperty("carbon.repo.write.mode", "true");
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(axis2Repo, axis2Conf);
            return new WSRegistryServiceClient(serverURL, username, password, configContext);
        }
    
        public static void main(String[] args) throws Exception {
            Registry registry = initialize();
    
            Collection newCol = registry.newCollection();
            newCol.setProperty("name", "WebLogin");
    
            registry.put("/_system/governance/permission/admin/login/WebLogin/", newCol);
        }
    }
    
    Change the CARBON_HOME variable path to the IS_HOME of your server. Further, to build this you need to add the plugins directory of a Governance Registry product to the class path. Then if you run this code, you get a collection called WebLogin created under /_system/governance/permission/admin

    Hope this article was useful for any WSO2 product user.

    Friday, October 10, 2014

    Downloading and running WSO2 Identity Server

    WSO2 Identity Server (IS) provide means for security and identity management for your web applications, services and API's. In it's latest version (5.0.0) it acts like an Enterprise Identity Bus (an idea of centrally managing the identity regardless of the standards being used). It's a versatile product to manage you application users security, entitle management and many more. See more information about the WSO2 identity server at http://wso2.com/products/identity-server/

    How to run WSO2 IS
    1. Download WSO2 IS from above URL itself.
    2. Extract the zip archive into a directory. Say the extracted dircetory is IS_HOME
    3. Navigate to the IS_HOME/bin in the console (terminal)
    4. Enter the following command
    $ ./wso2server.sh                       in Linux
    or
    $ ./wso2server.bat                 in Windows
    Once started you can access the management console by navigating the following URL

    http://localhost:9443/carbon

    You may login with default username (admin) and password (admin). When logged in you would see the management console as shown below.


    Tuesday, July 15, 2014

    Downloading and running WSO2 Complex Event Processor

    WSO2 CEP is a lightweight, easy-to-use, 100% open source Complex Event Processing Server licensed under Apache Software License v2.0. Modern enterprise transactions and activities consists of stream of events. Enterprises that monitor such events in real time and respond quickly to those environments undoubtedly have greater advantage over its competitors. Complex Event Processing is all about listening to such events and detecting patterns in real-time, without having to store those events. WSO2 CEP fulfills this requirements by identifying the most meaningful events within the event cloud, analyzes their impact and acts on them in real-time. It’s extremely high performing and massively scalable.


    How to run WSO2 CEP

    1. Extract the zip archive into a directory. Say the extracted dircetory is CEP_HOME
    2. Navigate to the CEP_HOME/bin in the console (terminal)
    3. Enter the following command  
            ./wso2server.sh       (In Linux)
            wso2server.bat        (In Windows)

    Once started you can access the management console by navigating the following URL

    http://localhost:9443/carbon

    You may login with default username (admin) and password (admin). When logged in you would see the management console as shown below.


    Thursday, March 20, 2014

    Downloading and running WSO2 API Manager

    WSO2 API Manager is fully open source product which allows you to create, publish and manage many aspects of APIs such as life cycle management, versioning, monetization, governance, security etc. A business has high potential for growth in using WSO2 API Manager as it allows managing APIs in a SOA environment in a decentralized manner.

    Let's start getting an insight about API Manager by downloading and running it in our local machine

    Download the latest WSO2 API Manager from http://wso2.com/products/api-manager/

    Extract the WSO2 API Manager into a directory. I'll refer to this directory as APIM_HOME. Navigate in to bin directory and run the WSO2 API Manager as follows.
    $ ./wso2server.sh                       in Linux
    or
    $ ./wso2server.bat                 in Windows
    
    You would see some content in the console and finally the Managemwnt console url, API publisher URL and the API store URL.

    Open up your favorite browser and open the Management console URL. 9443 is the default port, unless you have changed the offset.

    http://localhost:9443/carbon

    Note : If you are running more than one WSO2 product at a time, make sure you increment the <Offset> in PRODUCT_HOME/repository/conf/carbon.xml to avoid conflicting ports.

    You may be prompted for a security exception in the browser. Add the security exception. You would then be re-directed, after login with default user name (admin) and password (admin) to the API Management console as shown in the following. This is the administrative console use to manage aspects of the API.

    API Manager Management Console

    WSO2 API Manager also provides two more views, namely, API Publisher and API Store. API Publisher is the place where an API developer would create an API. He/She can also manage the life-cycle of the API in the publisher. API Store is the place where a typical API user would see, available APIs from publisher. He/She can subscribe to APIs and start using it for their own applications. Following two images are the windows of the API publisher and API store respectively in the API Manager 1.6.0.

    WSO2 API Manager Publisher
    WSO2 API Manager Store

    This is just a startup guide for WSO2 API Manager. I recommend you to play with this product and also to refer to the online documentation for further details.

    Cheers

    Monday, December 16, 2013

    Downloading and running WSO2 Enterprise Service Bus (ESB)

    WSO2 ESB is a fast and light Enterprise Service Bus. An ESB is a software component (a middle-ware application) that handles communication among various components that needs to transfer message to some other component and get their work done. Instead each component communicating with others directly, every component talks to ESB. ESB would then transfer messages to said formats and route it and get the work done.

    WSO2 ESB is built on top of Apache Synapse and has rich features to exploit. In this guide let's start of with downloading and running the WSO2 ESB.

    Download the latest WSO2 ESB from http://wso2.com/products/enterprise-service-bus/

    Extract the WSO2 ESB into a directory. I'll refer to this directory as ESB_HOME. Navigate in to bin directory and run the WSO2 ESB as follows.
    $ ./wso2server.sh                         in Linux  or
    > wso2server.bat                          in Windows
    You would see some content in the console and finally the Management console URL.
    Open up your favorite browser and point to the link.

    http://localhost:9443/carbon

    Note : You can only run one WSO2 product in it's default settings. If you are running more than one product at a time, make sure you increment the <Offset> in ESB_HOME/repository/conf/carbon.xml

    You may be prompted for a security exception in the browser. Add the security exception. You would then be re-directed to the ESB Management console as shown in the following after login in with default user name and password, which is 'admin'.


    Sunday, November 17, 2013

    Clustering WSO2 Governance Registry


    Note: Before reading this guide, I recommend reading my previous blog post on "Setting up WSO2 Governance Registry Partitions", because last few steps in this guide is similar to that of the previous post. You can still follow along without reading it though.

    In this guide we shall set up a WSO2 Governance Registry into a cluster. Cluster??? What's important in clustering any sort of product in the first place. Oh!!! That's a critical question. Anyhow, this could be a possible question in a semester paper of a subject in computer science. What could be that subject? Distributed Systems... I'm not sure. Well, whatever it is, I'll provide some simple answers why clustering an application can be useful, though these answers may not be suitable for a semester paper. :)
    • Clustering can be used to load balance between working nodes. This will reduce overhead that each node needs to handle by dividing work among partitions
    • Clustering enables application to withstand on sudden failures in one or more node as far as at least one node is up and running, decreasing the overall downtime of the service and providing high availability  
    • Clustering undoubtedly enables scalability and can increase the performance of the overall application
    OK.. enough of theory!!! Let's bogged down into clustering WSO2 Governance Registry as described below.

    Here we are going to demonstrate the clustered setup with three nodes of WSO2 Governance Registry (GREG), a WSO2 Elastic Load Balancer (ELB) and a database for storage, as shown below.


    We are going to set up the cluster in the local machine for testing, though, the steps would be the same if each component; ELB, GREG nodes and the DB, resides in different servers, except for appropriate IP address settings.

    First, we shall configure the WSO2 ELB, which is going to be in front of the three WSO2 GREG nodes. Load Balancers, in general help distribute the requests among the nodes. Download the WSO2 ELB from http://wso2.com/products/elastic-load-balancer/ and unzip it to a directory. I'll refer to load balancer home directory as ELB_HOME.

    Now open up the ELB_HOME/repository/conf/loadbalancer.conf and replace the governance domain as shown below.
        governance {
            hosts                   governance.cloud-test.wso2.com;
        #url_suffix         governance.wso2.com;
            domains   {
                wso2.governance.domain {
                    tenant_range *;
                    group_mgt_port 4321;
                    mgt {
                        hosts governance.cluster.wso2.com;
                    }
                }
            }
        }
    
    Next we need to edit the ELB_HOME/repository/conf/axis2/axis2.xml and uncomment the localMemberHost to expose the ELB to the members of the cluster (the GREG nodes that we are going to configure) as shown below.
    <parameter name="localMemberHost">127.0.0.1</parameter>
    Also change the localMemberPort to 5000 as shown below.
    <parameter name="localMemberPort">5000</parameter>
    Next you need to update your system's hosts file with an entry like the following, which is a simple mapping between an IP address and a hostname.
    127.0.0.1 governance.cluster.wso2.com
    In Linux, the file is /etc/hosts and in Windows the file is %systemroot%\system32\drivers\etc\hosts (In Windows to view this file you may have to enable the system to show hidden files)

    That's all on WSO2 ELB. We can now start the WSO2 ELB in terminal by running the following command in ELB_HOME/bin/
    $ ./wso2server.sh
    Let's now download the latest WSO2 GREG from http://wso2.com/products/governance-registry/, and unzip it into a directory. Then copy the GREG home directory to two more places for other two nodes. You can place all three nodes in the same directory and rename those by appending '_node1', '_node2' and '_node3'. Before we delve into configuring WSO2 GREG nodes, we need to create database to hold the shared node data.

    Let's now create database for the 'governance registry'. You can use the in-built H2 database, but it's recommended to use a database like MySQL in production systems. Therefore, we will use MySQL in this setup. If you don't have MySQL installed in Linux look in my previous post 'Installing MySQL in Linux'. Windows users can download and install using the MySQL installer package and it's very straight forward. To create a MySQL database for governance registry and populate it with the schema, enter the following to go into the MySQL prompt.
    $ mysql -u root -p
     
    mysql> create database wso2governance;
    Query OK, 1 row affected (0.04 sec)
    mysql> create database wso2apim;
    Query OK, 1 row affected (0.00 sec)
    Next we ought to exit from MySQL prompt. And, now we shall populate the databases we created with the schema. For that enter following commands. Don't forget to replace the GREG_HOME to any WSO2 GREG directory.
    $ mysql -u root -p wso2governance < GREG_HOME/dbscripts/mysql.sql
    $ mysql -u root -p wso2apim < GREG_HOME/dbscripts/apimgt/mysql.sql
    OK.. now database is also ready. We can now configure our WSO2 GREG nodes. Repeat the following steps in all the GREG nodes. The differences you have to make are noted where necessary.

    As a first step in clustering the nodes, we got to enable clustering in each GREG node, of course. This can be done by changing the enable attribute to 'true' as the following line in axis2.xml, which can be found in GREG_HOME/repository/conf/axis2 directory. And this needs to be done in all three nodes.
    <clustering class="org.wso2.carbon.core.clustering.hazelcast.HazelcastClusteringAgent" enable="true">
    * Change the GREG_HOME/repository/conf/axis2/axis2.xml as shown below
    <parameter name="membershipScheme">wka</parameter>
    <parameter name="domain">wso2.governance.domain</parameter>
    <parameter name="localMemberHost">governance.cluster.wso2.com</parameter>
    <parameter name="localMemberPort">4250</parameter>
    This is for joining to the multicast domain "wso2.governance.domain". Nodes with same domain belong to the clustering group. "wka" is for Well-Known Address based multicasting. "localMemberPort" port on other nodes needs to be different. Say 4251 and 4252. This is the TCP port on which other nodes contact this node.

    * In the <members> section, there needs to be a <member> tags with the details of the ELB or multiple ELBs (If we are having clusters of ELBs). The following shows the ELB with port 4321, which is the group management port we configured in the loadbalancer.conf in the ELB. Since we are having only one ELB, there is only one <member> tag.
    <members>
     <member>
         <hostName>127.0.0.1</hostName>
         <port>4321</port>
     </member>
    </members>
    * Next we need to edit the HTTP and HTTPS proxy ports in the GREG_HOME/repository/conf/tomcat/catalina-server.xml. Add a new attribute named proxyPort to 8280 in HTTP and 8243 in HTTPS. Attributes need to be added like proxyPort="8280" and proxyPort="8243" in the two <Connector> tags, respectively.

    * Next, since we are going to setup our nodes and the ELB in the local machine we need to avoid port conflicts. For this, set the <Offset> to 1 in the first node and 2 in
     the second node, 3 in the third node, in GREG_HOME/repository/conf/carbon.xml. You can put any Offset of your wish, but it has to be different if the nodes are running in the same machine. If these nodes are in different servers, this need not be done.

    * In carbon.xml we also need update the "HostName" and "MgtHostName" elements as follows
    <HostName>governance.cluster.wso2.com</HostName>
    <MgtHostName>governance.cluster.wso2.com</MgtHostName>
    * WSO2 Carbon platforms supports a deployment model in its architecture for components to act as two types of nodes in clustering setup. 'management' nodes and 'worker' nodes. 'management' nodes are used for changing configurations and deploying artifacts. 'worker' nodes are to process requests. But in WSO2 GREG there is no concept of request processing, all nodes are considered 'management' nodes. In a clustered setup, we got to configure this explicitly in axis2.xml. We need to change the value attribute to "mgt" of <property> tag of "subdomain". After the change, the property tags would look like the below.
    <!--
    Properties specific to this member
    -->
    <parameter name="properties">
        <property name="backendServerURL" value="https://${hostName}:${httpsPort}/services/"/>
        <property name="mgtConsoleURL" value="https://${hostName}:${httpsPort}/"/>
        <property name="subDomain" value="mgt"/>
    </parameter>
    * Next open up GREG_HOME/repository/conf/user-mgt.xml file and update the "datasource" property as follows to enable the user manager tables to be created in "wso2governance":
    <Property name="dataSource">jdbc/WSO2CarbonDB_mount</Property>
    * Next we to configure the shared 'config' and 'governance' registries, as I earlier pointed out to you to read my previous blog post "Setting up WSO2 Governence Registry Partitions". OK.. we shall configure this in each GREG_HOME/repository/conf/registry.xml and GREG_HOME/repository/conf/datasources/master-datasources.xml. First in registry.xml we need to add the following additional configs.

    Add a new <dbConfig>
    <dbConfig name="wso2registry_mount">
        <dataSource>jdbc/WSO2CarbonDB_mount</dataSource>
    </dbConfig>
    Add a new <remoteInstance>
    <remoteInstance url="https://localhost:9443/registry">
        <id>instanceid</id>
        <dbConfig>wso2registry_mount</dbConfig>
        <readOnly>false</readOnly>
        <enableCache>true</enableCache>
        <registryRoot>/</registryRoot>
        <cacheId>root@jdbc:mysql://localhost:3306/wso2governance</cacheId>
    </remoteInstance>
    Add the <mount> path for 'config' and 'governance'
    <mount path="/_system/config" overwrite="true">
        <instanceId>instanceid</instanceId>
        <targetPath>/_system/config</targetPath>
    </mount>
    <mount path="/_system/governance" overwrite="true">
        <instanceId>instanceid</instanceId>
        <targetPath>/_system/governance</targetPath>
    </mount>
    Next in master-datasources.xml add a new <datasource> as below. Do not change the existing <datasource> of <name> WSO2_CARBON_DB.
    <datasource>
        <name>WSO2_CARBON_DB_MOUNT</name>
        <description>The datasource used for registry and user manager</description>
        <jndiConfig>
            <name>jdbc/WSO2CarbonDB_mount</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
                <url>jdbc:mysql://localhost:3306/wso2governance</url>
                <username>root</username>
                <password>root</password>
                <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
    </datasource>
    As the final step modify the <datasource> for WSO2AM_DB as below.
    <datasource>
        <name>WSO2AM_DB</name>
        <description>The datasource used for API Manager database</description>
        <jndiConfig>
            <name>jdbc/WSO2AM_DB</name>
        </jndiConfig>
        <definition type="RDBMS">
            <configuration>
       <url>jdbc:mysql://localhost:3306/wso2apim?autoReconnect=true&amp;relaxAutoCommit=true</url>
                <username>root</username>
                <password>root</password>
                <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                <maxActive>50</maxActive>
                <maxWait>60000</maxWait>
                <testOnBorrow>true</testOnBorrow>
                <validationQuery>SELECT 1</validationQuery>
                <validationInterval>30000</validationInterval>
            </configuration>
        </definition>
    </datasource>
    Now we may run each WSO2 GREG node by running the following in GREG_HOME/bin
    $ ./wso2server.sh
    When all three nodes are up and running, the ELB console should have printed something similar to below, indicating that nodes have successfully joint the cluster.
    [2013-11-12 16:52:29,260]  INFO - HazelcastGroupManagementAgent Member joined [271050b5-69d0-468d-9e9e-29557aa550ef]: governance.cluster.wso2.com/127.0.0.1:4252
    [2013-11-12 16:52:32,314]  INFO - MemberUtils Added member: Host:127.0.0.1, Remote Host:null, Port: 4252, HTTP:9766, HTTPS:9446, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true
    [2013-11-12 16:52:32,315]  INFO - HazelcastGroupManagementAgent Application member Host:127.0.0.1, Remote Host:null, Port: 4252, HTTP:9766, HTTPS:9446, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true joined application cluster
    [2013-11-12 16:53:01,042]  INFO - TimeoutHandler This engine will expire all callbacks after : 86400 seconds, irrespective of the timeout action, after the specified or optional timeout
    [2013-11-12 16:55:34,655]  INFO - HazelcastGroupManagementAgent Member joined [912fe7db-7334-467c-a6a7-e6929e652edb]: governance.cluster.wso2.com/127.0.0.1:4251
    [2013-11-12 16:55:38,707]  INFO - MemberUtils Added member: Host:127.0.0.1, Remote Host:null, Port: 4251, HTTP:9765, HTTPS:9445, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true
    [2013-11-12 16:55:38,708]  INFO - HazelcastGroupManagementAgent Application member Host:127.0.0.1, Remote Host:null, Port: 4251, HTTP:9765, HTTPS:9445, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true joined application cluster
    [2013-11-12 16:57:05,136]  INFO - HazelcastGroupManagementAgent Member joined [cc177d58-1ec1-473e-899c-9f154303e606]: governance.cluster.wso2.com/127.0.0.1:4250
    [2013-11-12 16:57:09,232]  INFO - MemberUtils Added member: Host:127.0.0.1, Remote Host:null, Port: 4250, HTTP:9764, HTTPS:9444, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true
    [2013-11-12 16:57:09,232]  INFO - HazelcastGroupManagementAgent Application member Host:127.0.0.1, Remote Host:null, Port: 4250, HTTP:9764, HTTPS:9444, Domain: wso2.governance.domain, Sub-domain:mgt, Active:true joined application cluster
    Great!!!. Now we may access the Management Console by browsing the https://governance.cluster.wso2.com:8243/carbon and now the WSO2 GREG is clustered. Every processing that comes to ELB will be distributed among the GREG nodes, providing the scalability and high availability.

    Sunday, October 27, 2013

    Setting up WSO2 Governance Registry Partitions

    In this brief guide, I'll walk you through setting up, WSO2 Governance registry setup in a remote machine, and another local setup (the node) to share with the remote instance. I'm going to setup the remote instance locally as well, so that it's easy for you to set this up, in the same machine (But the procedure would mostly be the same on to an actual remote setup)

    As you may know, WSO2 Governance registry is separated into three sub registries;
    •     Config registry - Stores the configurations and related information of a product
    •     Governance registry - Stores governance artifacts and other related information
    •     Local registry - Stores information that is local to a node in a cluster
    Local registry, as its name implies, have to be local to that instance. Other two registries can be shared.
    To start of with experimenting this setup with WSO2 Governance Registry, go ahead and download the latest stable WSO2 Governance Registry product from http://wso2.com/products/governance-registry/ After downloading, extract the zip file to a location of your interest, and copy the entire folder to another location to have a perception of the shared instance.

    To avoid confusion, let me rename the directory name of the shared instance to wso2greg-4.6.0_remote. The version number of the extracted zip file may be different from this at the time of your download. Follow this with the version and change the procedure accordingly to reflect the version that you have downloaded. Let the local instance directory name be wso2greg-4.6.0. I've placed the two directories in my home directory. Therefore the two directories are, $HOME/wso2greg-4.6.0 and $HOME/wso2greg-4.6.0_remote. I'll refer to these two directories as GREG_HOME in respective contexts.

    WSO2 governance registry uses inbuilt H2 database to store data related to above three registries. In a production environment however, it's recommended to use some other RDBMS such as MySQL as the registry DB. Therefore, in this tutorial, we shall use MySQL as the DB for the remote shared partition.

    To install MySQL database point to my above blog post "Installing MySQL in Linux" 

    Assuming you have installed MySQL DB and running, you can now create the database named registrydb (the name can be anything you like) in MySQL as follows,

    mysql> create database registrydb;
    

    Let's first setup our remote shared instance (i.e. the directory named wso2greg-4.6.0_remote)

    In fact, there is nothing much to do in this setup except modifying the configuration file named master-datasources.xml which you can find in GREG_HOME/repository/conf/datasources/ to use MySQL, instead of the built-in H2 database. Change the <datasource> of WSO2_CARBON_DB as shown below.

            <datasource>
                <name>WSO2_CARBON_DB</name>
                <description>The datasource used for registry and user manager</description>
                <jndiConfig>
                    <name>jdbc/WSO2CarbonDB</name>
                </jndiConfig>
                <definition type="RDBMS">
                    <configuration>
                        <url>jdbc:mysql://127.0.0.1:3306/registrydb</url>
                        <username>root</username>
                        <password>root</password>
                        <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                        <maxActive>50</maxActive>
                        <maxWait>60000</maxWait>
                        <testOnBorrow>true</testOnBorrow>
                        <validationQuery>SELECT 1</validationQuery>
                        <validationInterval>30000</validationInterval>
                    </configuration>
                </definition>
            </datasource>

    Note the <url>. You may use the phrase "localhost" instead of the loopback address 127.0.0.1 IP address. Further, change the port on which your MySQL runs. (3306 is the default configured MySQL port.)
    registrydb part of the URL indicates the database we created earlier.

    We need to copy the MySQL JDBC driver (a .jar file), which you can download from http://www.mysql.com/products/connector/, to GREG_HOME/components/lib/. And, this step needs to be done in the other node as well.

    We can now start this instance of the WSO2 Governance registry by issuing the following command from GREG_HOME/bin

    $ ./wso2server.sh -Dsetup

    Here the -Dsetup option is to populate the created 'registrydb' in MySQL. We can now access the management console by navigating to the https://localhost:9443/carbon/ URL from your browser.

    Now we can configure the other node (our local instance that's going to share the 'Config' and 'Governance' registries of the remote partition that we have already started). Therefore, what needs to happen is that, to inform this node about the remote 'Config' and 'Governance' registries that we intend to use. This is done in WSO2 Governance Registry by properly configuring the registry.xml and the master-datasources.xml configuration files.

    Let's configure the registry.xml file. We need to tell this registry partition that we are going to use a remote 'Config' and 'Governance' registries. This is done by adding the following in the registry.xml file.

        <mount path="/_system/config" overwrite="true">
            <instanceId>mountInstance</instanceId>
            <targetPath>/_system/config</targetPath>
        </mount>
    
        <mount path="/_system/governance" overwrite="true">
            <instanceId>mountInstance</instanceId>
            <targetPath>/_system/governance</targetPath>
        </mount>

    And further, we have to have a way to inform the mount instance location. That's done by adding the following in registry.xml.

        <remoteInstance url="https://x.x.x.x:9443/registry">
            <id>mountInstance</id>
            <dbConfig>mountregistry</dbConfig>
            <readOnly>false</readOnly>
            <enableCache>true</enableCache>
            <registryRoot>/</registryRoot>
            <cacheId>root@jdbc:mysql:@127.0.0.1:3306:registrydb</cacheId>
        </remoteInstance> 
    

    Where x.x.x.x is the IP address of the remote partition. Since, the remote instance that we already started is in localhost that x.x.x.x = 127.0.0.1 (the loopback ip address). If you are setting this up in a true remote setup, change that IP address accordingly. Note that <id> tag matches the <instanceid> tag in the <mount> we configured earlier.

    Now the registry partition location is been informed. Now we got to say, where the database of the remote instance resides. That database could ideally be in any location within the reachable network. It has to be configured in the master-datasources.xml file. Before that, we have to add one more addition to registry.xml file. It's listed below.

        <dbConfig name="mountregistry">
            <dataSource>jdbc/WSO2MountRegistryDB</dataSource>
        </dbConfig>
    

    "jdbc/WSO2MountRegistryDB" will be a reference to the relevant <datasource> that we would next configure in the master-datasources.xml file. Now, let's move to master-datasources.xml file. There we would keep the default H2 database for the local registry. Additionally we got to say the DB instance where the 'Config' and 'Governance' registries reside. Add the following <datasource> in master-datasources.xml to achieve that.

            <datasource>
                <name>WSO2_MOUNT_REGISTRY_DB</name>
                <description>The datasource used for registry and user manager</description>
                <jndiConfig>
                    <name>jdbc/WSO2MountRegistryDB</name>
                </jndiConfig>
                <definition type="RDBMS">
                    <configuration>
                        <url>jdbc:mysql://127.0.0.1:3306/registrydb</url>
                        <username>root</username>
                        <password>root</password>
                        <driverClassName>com.mysql.jdbc.Driver</driverClassName>
                        <maxActive>120</maxActive>
                        <maxWait>900000</maxWait>
                        <testOnBorrow>true</testOnBorrow>
                        <validationQuery>SELECT 1 FROM DUAL</validationQuery>
                        <validationInterval>30000</validationInterval>
                    </configuration>
                </definition>
            </datasource>
    

    I guess we are all set, except for one thing. Since we are going to run both the remote and local setup in the local machine itself, if you run the currently configured node, you would see an exception thrown in the console. The reason for this is that, we can't run two WSO2 products at the same time, since both would attempt to run on the same default port 9443. To avoid the conflict, we should set the offset for the next server that we are going to run in the carbon.xml in GREG_HOME/repository/conf. Open up carbon.xml and change the value for <offset> to 1. This will make this instance to start of with the port 9444. If you are running this setup in two different machines you may not need to do this change, though doing so would do no harm either.

    Phew!!!. All done. Now we shall start this instance in the same way we started the earlier remote instance. In the console, you should see the following three lines among others, which indicate that two registries; 'Config' and 'Governance' have been mounted in the 'mountregistry'.

     [2013-10-21 16:00:46,379]  INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Configured Registry in 116ms
     [2013-10-21 16:00:46,408]  INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Connected to mount at mountregistry in 3ms
     [2013-10-21 16:00:46,606]  INFO {org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService} -  Connected to mount at mountregistry in 0ms
    

    You may access the Management Console by browsing https://localhost:9444/carbon/ URL. In the Management console, click 'Browse' and expand the _system in the tree view. You should see blue arrow in front of 'config' and 'governance' nodes as shown in the following screenshot, indicating that it's mounted in a remote partition.


    Saturday, October 19, 2013

    Downloading and running WSO2 Governance Registry


    WSO2 Governance registry is fully open source, Service Oriented Architecture (SOA) integrated registry for storing and managing artifact metadata.

    In this short guide, I'll walk you through the process of how to download the WSO2 Governance Registry and start it in your machine and accessing it with its in-built web based management console (A Web User Interface (UI)), for managing the metadata.

    The process is just simple. Download the latest release binary zip file from http://wso2.com/products/governance-registry/

    Once you download the zipped archive, extract it to a directory of your liking. Let's assume the extracted directory be $(HOME_DIRECTORY)/wso2greg-4.5.3/ and let me call this directory $(GREG_HOME). You must have Java installed and JAVA_HOME set to successfully start the product. See my previous post "Installing Developer Tools in Linux" to see how to install and configure java in Linux.

    Navigate to $(GREG_HOME)/bin and execute the following to run the WSO2 Governance Registry.
     $ ./wso2server.sh                                (In Linux)
     > wso2server.bat                                 (In Windows)
    
    This will start the WSO2 Governance regiatry with all the default configurations, and you should see an output in console. In the end of the output you should see an output like the following.
    Mgt Console URL  : https://192.168.2.1:9443/carbon/
    
    Copy and paste the above URL in your favorite browser. You should see the WSO2 Governance Registry management console login screen. You can use the default Admin user credentials of which username and password being 'admin' to access the registry. Once you access you are ready to store and manage different artifacts in WSO2 Governance Registry. Following is a typical screen shot of the first page that you would see when you logged in.



    Good Luck in using the product.