import java.security.PrivilegedAction;
import java.util.Properties;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import com.sun.jna.platform.win32.Sspi.SecBufferDesc;
import waffle.windows.auth.IWindowsCredentialsHandle;
import waffle.windows.auth.impl.WindowsAccountImpl;
import waffle.windows.auth.impl.WindowsCredentialsHandleImpl;
import waffle.windows.auth.impl.WindowsSecurityContextImpl;
public class Example {
private final Properties env;
public static void main(String[] args) {
new Example();
}
public Example() {
env = new Properties();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.referral", "ignore");
env.put("javax.security.sasl.qop", "auth-conf");
env.put("java.naming.provider.url", "ldap://<host>.<realm>:389");
env.put("java.naming.security.authentication", "GSSAPI");
System.setProperty("java.security.auth.login.config", "<path>\\gssapi-waffle.conf");
System.setProperty("java.security.auth.policy", "<path>\\jaas.policy");
byte[] serviceTicket = getServiceTicketSSPI("LDAP/<host>.<realm>");
env.put("javax.security.auth.kerberos.KerberosTicket", serviceTicket);
testLdapServiceLogin();
}
private void testLdapServiceLogin() {
LoginContext lc = null;
try
{
lc = new LoginContext("Jaas");
lc.login();
LdapContext ldapContext = (LdapContext) Subject.doAs(lc.getSubject(), new PrivilegedAction<LdapContext>() {
@Override
public LdapContext run() {
InitialLdapContext result = null;
try{
result = new InitialLdapContext(env, null);
}catch(NamingException ex){
ex.printStackTrace();
}
return result;
}
});
System.out.println(ldapContext);
}
catch (LoginException ex)
{
ex.printStackTrace();
}
}
public byte[] getServiceTicketSSPI(final String serviceName) {
final String securityPackage = "Kerberos";
IWindowsCredentialsHandle clientCredentials = null;
WindowsSecurityContextImpl clientContext = null;
final String currentUser = WindowsAccountImpl.getCurrentUsername();
try {
clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage);
clientCredentials.initialize();
// initial client security context
clientContext = new WindowsSecurityContextImpl();
clientContext.setPrincipalName(currentUser);
clientContext.setCredentialsHandle(clientCredentials);
clientContext.setSecurityPackage(securityPackage);
final SecBufferDesc continueToken = null;
do {
clientContext.initialize(clientContext.getHandle(), continueToken, serviceName);
} while (clientContext.isContinue());
return clientContext.getToken();
} finally {
if (clientContext != null) {
clientContext.dispose();
}
if (clientCredentials != null) {
clientCredentials.dispose();
}
}
}
}