Connecting to MSSQL SERVER using Microsoft Java ODBC driver and Kerberos

I did not find a lot of documentation for connecting to SQL SERVER using Kerberos authentication and JAVA. So I decided to write this little blog post up.

The key piece of information is using authenticationScheme=JavaKerberos in the connection string.
This works on both Windows and Linux Operating System as long as you have Kerberos ticket. You can verify if you have a Kerberos ticket by typing klist on the command line.
You should see something like the following for your user.

[user1@vm01 ~]$ klist
Ticket cache: FILE:/tmp/krb5cc_16777216_kbQnZ2
Default principal: testuser1@CORP.COMPANY.NET
 
Valid starting     Expires            Service principal
10/22/14 07:23:58  10/22/14 17:23:58  krbtgt/CORP.COMPANY.NET@CORP.COMPANY.NET
    renew until 10/29/14 07:23:58
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.microsoft.sqlserver.*;

public class main {
	public static void main(String[] args) {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String connectionUrl = "jdbc:sqlserver://SQLSERVER01;instanceName=SQLINSTANCE01;database=Inventory;integratedSecurity=true;authenticationScheme=JavaKerberos";
		
		try {
			Connection con = java.sql.DriverManager.getConnection(connectionUrl);
			System.out.println("connected...");
			
			String SQL = "select * from dbo.table01";
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery(SQL);
			

			while (rs.next())
			{
				System.out.println(rs.getString(1));
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s