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: [email protected] Valid starting Expires Service principal 10/22/14 07:23:58 10/22/14 17:23:58 krbtgt/[email protected] 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();
}
}
}