How to set JAAS configuration programmatically

Sometimes you need to set java.security.auth.login.config property programmatically. Here is how you can do it. Just modify LoginConfig class to satisfy your needs:

import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;

public class JaasConfigurationExample {

    public void work() {
        LoginConfig loginConfig = new LoginConfig(keyTabLocation, servicePrincipalName, debug);
        LoginContext lc = new LoginContext("", subject, null, loginConfig);
    }
    
    private static class LoginConfig extends Configuration {
        private String keyTabLocation;
        private String servicePrincipalName;
        private Boolean debug;
    
        public LoginConfig(String keyTabLocation, String servicePrincipalName, Boolean debug) {
            this.keyTabLocation = keyTabLocation;
            this.servicePrincipalName = servicePrincipalName;
            this.debug = debug;
        }
    
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<>();
            options.put("useKeyTab", "true");
            options.put("keyTab", keyTabLocation);
            options.put("principal", servicePrincipalName);
            options.put("storeKey", "true");
            options.put("doNotPrompt", "true");
            if (debug) {
                options.put("debug", "true");
            }
            options.put("isInitiator", "false");
            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry(
                            "com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)
                    };
        }
    }
}

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

Leave a Reply

Your email address will not be published.