/*
 * Basic Java Kerberos Testing tool
 * Luke H 2025 0.1
 *
 * Update and Set the following items, then compile the code.
 * Requires  a Valid jass Configuration.
 * Recommended use with debugging flags at run time if not set in jass.conf. 
 * -Dsun.security.krb5.debug=true -Dsun.security.spnego.debug=true
 *
 * KRB5_CONF_PATH
 * KEYTAB_PATH
 * PRINCIPAL_NAME
 * JAAS_CONFIG_PATH
 */

import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.Subject;
import java.security.PrivilegedAction;

public class KerberosTest {

    // Adjust these constants based on your environment
    private static final String KRB5_CONF_PATH = "/etc/krb5.conf";
    private static final String KEYTAB_PATH = "/path/to/your/service.keytab";
    private static final String PRINCIPAL_NAME = "your_service_principal@YOUR.REALM";
    private static final String JAAS_CONFIG_PATH = "jaas.conf";

    public static void main(String[] args) {
        // Set system properties required for Kerberos login
        System.setProperty("java.security.krb5.conf", KRB5_CONF_PATH);
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
        System.setProperty("java.security.auth.login.config", JAAS_CONFIG_PATH);

        try {
            // Create a LoginContext using the entry defined in jaas.conf
            LoginContext loginContext = new LoginContext("KerberosLogin");
            loginContext.login();

            Subject serviceSubject = loginContext.getSubject();
            System.out.println("Authentication successful for: " + serviceSubject);

            // Run privileged action as the authenticated Subject
            Subject.doAs(serviceSubject, (PrivilegedAction<Void>) () -> {
                System.out.println("Executing privileged action as " + PRINCIPAL_NAME);
                // Place any Kerberos-authenticated operations here
                return null;
            });

            loginContext.logout();
            System.out.println("Logout successful.");

        } catch (LoginException e) {
            System.err.println("Authentication failed: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("Unexpected error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

