Thursday, December 31, 2015

Setting up Couchbase Server to work with Microsoft Active Directory LDAP

Hi all!

So you want to authenticate users access to Couchbase through your Active Directory LDAP service.

Couchbase has that ability.
You can actually map every user to one of three access permissions levels (as for v4.1)
1. Full Admin
2. Read Only
3. No access

I assume the following:
1.You already have an Active Directory up and running
If not, please refer to here or here for setup instructions.
2. You already have Couchbase already installed (on a Linux Distro)
If not, please refer to those guides: RHEL or Debian

As for v4.1 of Couchbase, only the Linux distros support the LDAP, it's not available on Windows nor MacOS.

My setup here is an Azure Windows server 2012 R2 VM with Active Directory and a local Ubuntu 14.04.3 LTS VM with Couchbase v4.1 installed.

In the setting of your Linux Couchbase you will find a tab called LDAP Auth Setup

To fully understand how the LDAP authentication works with Couchbase,
please read Couchbase's documentation.

So first thing first, install the saslauthd
Pay attention if you are using RHEL or Ubutntu, paths and instructions are a bit different.

TL;DR version in Ubuntu
1. sudo apt-get update
2. sudo apt-get install sasl2-bin
3. sudo nano /etc/default/saslauthd
4. Change START=yes, MECHANISMS="ldap"
5. Save and quit (ctrl+x)
6. switch to sudo (sudo -u)
7. change permission for /var/run/saslauthd and /var/run/saslauthd/mux to 755 so couchbase user can access them.
8. cd to /etc folder
9. if saslauthd.conf does not exist - touch it and add 755 permissions.
10. configure the file as follows:

 ldap_servers: ldap://yourmachineaddress:389  
 ldap_search_base: dc=couchbase,dc=org  
 ldap_filter: (sAMAccountName=%u)  
 ldap_bind_dn: CN=[admin user],CN=Users,DC=couchbase,DC=org  
 ldap_password: [admin password]  
 ldap_auth_method: bind  
 ldap_version: 3  
 ldap_use_sasl: no  
 ldap_restart: yes  
 ldap_deref: no  
 ldap_start_tls: no  

ldap_servers is your AD server
ldap_search_base is on what domain you would like to search users (here it's on AD)
ldap_filter is what you want to return
ldap_bind_dn is a user with admin privileges permissions who can search the AD user tree.
ldap_password the admin user password

11. Open Active Directory ports for LDAP, 389 (TCP+UDP), 3268,3269, 636 (UDP)
12. You can test your active directory connection with JXplorer
13. Restart your salsauthd service - sudo service saslauthd restart
14.  Test it! - sudo -u couchbase /usr/sbin/testsaslauthd -u -p mypassword -f /var/run/saslauthd/mux
15. if you have permissions and set it all up as above you should get a success message.
the username and the password here are the ones you want to check, not the ldap admin.

now let's use it on the Couchbase console!
1. Login to your cluster management console and hit settings -> LDAP Auth setup.
2. Enable LDAP
3. Choose your default behavior - if you don't specify the username anywhere
4. Write down some users or groups in each box
5. Hit save
6. Test it (on the right)
7. If everything is ok - you should get something like "user 'x' has 'Full Admin' access
because I've listed that user under the Full Admin.

8. now sign out and try logging in with the Active Directory Credentials.

If I will get the password wrong - I won't be able to access, as expected.

In case you AD server is unreachable, you would still be able to log in through your regular Couchbase accounts.

Thats all!
Hope you enjoyed.


Thursday, December 24, 2015

Couchbase Mobile - Part 1 - Couchbase lite & P2P

Hi all
Couchbase Mobile solution is thrilling innovative and yet fairly simple - it just works!

In this blog we will cover the Couchbase Lite peer-to-peer capabilities, how
you can very easily, to connect two Couchbase Lite databases from two different
devices together using the built in replication.

In general the Couchbase's Mobile solution consists of 3 parts,
1) Couchbase Server
2) Sync Gateway
3) Couchbase Lite

Couchbase server holding all the data and can be synced through Sync Gateway to the Embedded Couchbase lite and vice versa.

On this part I will focus on the Couchbase Lite and how to set up P2P replication on .Net platform (but it's pretty much the same on every other platform)

So before we get into some coding, what is Couchbase Lite?
Couchbase lite is an opened-source, embedded document database with built-in abilities of Key/Values store, Indexing (aka Views), and above all - Replication.
Replication is what making that little Database so special.
I can replicate itself to the sync gateway or to any other Couchbase Lite database,
It features security through authentication and segregation of data from one device to another via concept that called channels.

What is replication? as it sounds - duplicate\copy data from one local database to another target, which can be either another local database or the sync gateway.
The API which the replication is using is basically a REST API, which every Couchbase lite is implementing.

So let's build a simple App that replicates data between two peers!
as I said, I've used C# .Net here (don't run away :) ), but the code is actually pretty much the same in Java.
To properly test that project, you might have to use two computers in a network.
but, because we will create the database locally in the folder of the app, a copy to a different location and using separate ports will be ok as well.

First of all, Open Visual Studio 2015 (can be community) as an administrator, In a simple WPF form.

right click on References -> Manage Nuget Packages...

Next, add the Couchbase Lite which is available via nuget package.

Search for Couchbase Lite and install the latest Couchbase.Lite and Couchbase.Lite.Listener.
at the time of the writing of this blog, the latest is 1.1.2.

Once installed, Copy and paste the following code to your MainWindow XAML page.

 <Window x:Class="CouchbaseP2P_Blog.MainWindow"  
     Title="Couchbase Lite P2P Example" Height="350" Width="525">  
       <ColumnDefinition Width="auto"/>  
       <ColumnDefinition Width="100"/>  
       <ColumnDefinition Width="*"/>  
       <RowDefinition Height="auto"/>  
       <RowDefinition Height="*"/>  
     <StackPanel Grid.Row="0" Grid.Column="0">  
       <TextBlock Text="Replicate to (address): " Margin="1"/>  
       <TextBlock Text="Replicate to (port): " Margin="1"/>  
       <TextBlock Text="Listen On Port" Margin="1"/>  
       <Button Content="Start Replicating" Click="StartReplcatingClick"/>  
       <Button Content="Start P2P Listener" Click="StartListenerClick"/>  
     <StackPanel Grid.Row="0" Grid.Column="1">  
       <TextBox Text="{Binding ReplicateToAddress}" />  
       <TextBox Text="{Binding ReplicateToPort}"/>  
       <TextBox Text="{Binding ListenOnPort}"/>  
       <TextBlock Text="{Binding IsReplicating}" Margin="1"/>  
       <TextBlock Text="{Binding IsListening}" Margin="1"/>  
     <StackPanel Grid.Column="0" Grid.Row="1" Margin="0 10 0 0">  
       <Button Content="Insert" Click="InsertDocumentClick" />  
       <Button Content="Read" Click="GetDocumentClick" />  
     <StackPanel Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2" Margin="0 10 0 0">  
       <TextBox Text="{Binding DocumentId}" Margin="1"/>  
       <TextBox Text="{Binding DocumentText}" TextWrapping="Wrap" AcceptsReturn="True" MinHeight="100"/>  

That code above, should look similar to the following output

Next we need to connect the XAML doc to the CodeBehind.
That sample is not MVVM for simplicity - but I did used binding.

First lets initialize the Database and set it to be created locally in our working folder,
We will call that method from the constructor.
Steps are,
  1.  Get the path where you want your database to be created
  2. Create manager with that path
  3. Initialize Database with the manager.
Note: the const DB_NAME in our case will be "sampledb" and it must have all lowercase letter.

     private void InitializeDatabase()  
        _dbPath = new DirectoryInfo(Environment.CurrentDirectory);  
        _manager = new Manager(_dbPath, ManagerOptions.Default);  
        _database = _manager.GetDatabase(DB_NAME);  

Add code to start Couchbase Lite Listener
Just create a new listener with the wanted port and the desired database name.

     private void StartListenerClick(object sender, RoutedEventArgs e)  
       _listener = new CouchbaseLiteTcpListener(_manager, ushort.Parse(ListenOnPort), DB_NAME);  
       IsListening = "Listening";

And lastly - the code for our replication
Steps are:

  1. Create pull/push replication to address and port
  2. Decide whether you want continuous replication of one time
  3. Start the replication.

     private void StartReplcatingClick(object sender, RoutedEventArgs e)  
         if (_pulls == null) _pulls = new List();  
         if (_pushes == null) _pushes = new List();  
         var pull = _database.CreatePullReplication(CreateSyncUri(ReplicateToAddress, int.Parse(ReplicateToPort), DB_NAME));  
         var push = _database.CreatePushReplication(CreateSyncUri(ReplicateToAddress, int.Parse(ReplicateToPort), DB_NAME));  
         pull.Continuous = true;  
         push.Continuous = true;  
         IsReplicating = "Replicaing!";  
       catch (Exception ex)  
     private Uri CreateSyncUri(string hostname, int port, string dbName)  
       Uri syncUri = null;  
       string scheme = "http";  
         var uriBuilder = new UriBuilder(scheme, hostname, port, dbName);  
         syncUri = uriBuilder.Uri;  
       catch (UriFormatException e)  
         Debug.WriteLine(string.Format("{0}: Cannot create sync uri = {1}", dbName, e.Message));  
       return syncUri;  

Lets add a bit of code for Insert and Get

     private void InsertDocumentClick(object sender, RoutedEventArgs e)  
       if (string.IsNullOrWhiteSpace(DocumentId))  
         MessageBox.Show("Please specify ID");  
       var document = _database.GetDocument(DocumentId);  
       var properties = JsonConvert.DeserializeObject<Dictionary<string, object>>(DocumentText);  
       var revision = document.PutProperties(properties);  
     private void GetDocumentClick(object sender, RoutedEventArgs e)  
       var doc = _database.GetDocument(DocumentId);  
       DocumentText = JsonConvert.SerializeObject(doc.Properties, Formatting.Indented);  

All we have to do now is to connect all the bindings you see in the XAML page and to implement INotifyPropertyChanged

Here is the full Code Behind
The full project can be found on Github

Now, in order to use it and test your replication, follow the following steps:

  1. Copy your executable folder to 2 different folders (i.e. Client1 and Client2)
  2. Start both clients under Administrator privileges
  3. Configure Client1 listening Port as 49840
  4. Configure Client2 listening Port as 49841
  5. Configure Client1 replication address to localhost and port 49841
  6. Configure Client2 replication address to localhost and port 49840
  7. Once it started replicating, Add a sample JSON with an ID on Client1 and test it on Client2
    and vice versa.

That's all!
We've built our first Couchbase lite replication in c# without all the fuss and hard work of the replication logic!

Next time - A bit more of Coucbase lite replications and deep dive into views.

Please check API, and quickstarts here

Merry xmas!