Thursday, November 8, 2007

Samba in Java

I have known about this great open-source library for a long time and have utilized it in just about every java application deployed on a windows corporate intranet - and I am always surprised that so few people know about it. I am referring to the JCIFS library that implements the CIFS/SMB networking protocol in 100% Java.

Windows (NTLM) authentication against a domain controller is as simple as specifying a servlet filter and configuring its properties. ( The below is shamefully :-) copied from the FAQ )


<filter>
<filter-name>NtlmHttpFilter</filter-name>
<filter-class>jcifs.http.NtlmHttpFilter</filter-class>

<init-param>
<param-name>jcifs.http.domainController</param-name>
<param-value>192.168.2.15</param-value>
</init-param>
<init-param>
<param-name>jcifs.smb.client.logonShare</param-name>
<param-value>JCIFSACL</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>NtlmHttpFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


Arbitrary java clients (other than webapps) could use something similar to:

UniAddress mydomaincontroller = UniAddress.getByName( "192.168.1.15" );
NtlmPasswordAuthentication mycreds = new NtlmPasswordAuthentication( "ntdom", "user", "pass" );
try {
SmbSession.logon( mydomaincontoller, mycreds );
// SUCCESS
return true;
} catch( SmbAuthException sae ) {
// AUTHENTICATION FAILURE
return false;
} catch( SmbException se ) {
// NETWORK PROBLEMS?
se.printStackTrace();
}


Accessing shared files is as simple as:

try {
SmbFile dummy = new SmbFile( "smb://domain;username:password@server/share/path/to/file.txt" );
SmbFile dest = new SmbFile("smb://server/share/path/to/dir/");
dummy.copyTo(dest);

} catch( SmbAuthException sae ) {
sae.printStackTrace();
} catch( SmbException se ) {
// NETWORK PROBLEMS?
se.printStackTrace();
}

No comments: