oozie java api submit job, kerberos Authentication error - kerberos

I hava hadoop-2.7 cluster, oozie-4.0.1 running in secure mode(with kerberos).
All are well. I can use cli commands submit job as follow:
Kinit myuser
oozie job -oozie https://10.1.130.10:21003/oozie -config job.properties -run
but I use oozie java api submit job, kerberos exception occur.
Exception in thread "main" AUTHENTICATION : Could not authenticate, GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
at org.apache.oozie.client.AuthOozieClient.createConnection(AuthOozieClient.java:150)
at org.apache.oozie.client.OozieClient.getSupportedProtocolVersions(OozieClient.java:577)
at org.apache.oozie.client.OozieClient.validateWSVersion(OozieClient.java:538)
at org.apache.oozie.client.OozieClient.createURL(OozieClient.java:651)
at org.apache.oozie.client.OozieClient.access$100(OozieClient.java:103)
at org.apache.oozie.client.OozieClient$ClientCallable.call(OozieClient.java:803)
at org.apache.oozie.client.OozieClient.run(OozieClient.java:999)
at com.huawei.oozie.OozieMain.main(OozieMain.java:47)
Caused by: org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
at org.apache.hadoop.security.authentication.client.KerberosAuthenticator.doSpnegoSequence(KerberosAuthenticator.java:334)
at org.apache.hadoop.security.authentication.client.KerberosAuthenticator.authenticate(KerberosAuthenticator.java:206)
at org.apache.hadoop.security.authentication.client.AuthenticatedURL.openConnection(AuthenticatedURL.java:215)
at org.apache.oozie.client.AuthOozieClient.createConnection(AuthOozieClient.java:144)
... 7 more
Caused by: GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
at sun.security.jgss.krb5.Krb5InitCredential.getInstance(Krb5InitCredential.java:147)
at sun.security.jgss.krb5.Krb5MechFactory.getCredentialElement(Krb5MechFactory.java:122)
at sun.security.jgss.krb5.Krb5MechFactory.getMechanismContext(Krb5MechFactory.java:187)
at sun.security.jgss.GSSManagerImpl.getMechanismContext(GSSManagerImpl.java:224)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:212)
at sun.security.jgss.GSSContextImpl.initSecContext(GSSContextImpl.java:179)
at org.apache.hadoop.security.authentication.client.KerberosAuthenticator$1.run(KerberosAuthenticator.java:313)
at org.apache.hadoop.security.authentication.client.KerberosAuthenticator$1.run(KerberosAuthenticator.java:288)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.authentication.client.KerberosAuthenticator.doSpnegoSequence(KerberosAuthenticator.java:288)
... 10 more
my java code as follow:
System.setProperty("java.security.auth.login.config", System.getProperty("user.dir") + File.separator + "conf"
+ File.separator + "jaas.conf ");
System.setProperty("java.security.krb5.conf", System.getProperty("user.dir") + File.separator + "conf"
+ File.separator + "krb5.conf ");
String url = "https://10.137.60.60:21003/oozie";
AuthOozieClient wc = new AuthOozieClient(url);
wc.setDebugMode(1);
Properties conf = wc.createConfiguration();
FileReader fr = new FileReader("conf/job.properties");
conf.load(fr);
System.out.println(conf.toString());
String jobId = wc.run(conf);
System.out.println("Workflow job submitted");
while (wc.getJobInfo(jobId).getStatus() == WorkflowJob.Status.RUNNING)
{
System.out.println("Workflow job running ...");
Thread.sleep(3 * 1000);
}
System.out.println("Workflow job completed ...");
System.out.println(wc.getJobInfo(jobId));
my conf/jaas.conf as follow:
Client {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
keyTab="D:/workspace/4.4-billing/Oozie/conf/oozie.keytab"
principal="oozie#HADOOP.COM"
useTicketCache=false
storeKey=true
debug=true;
};
can anyone help me ? I know oozie use hadoop-auth jar. but how to set keytab, write authenticate code, I cannot.

set your kerberos user account as
conf.setProperty(OozieClient.USER_NAME, "xyz");
oozieClient.run(conf);

Related

Generate SPNEGO Token Failured

I tried to generate the token which can be used as the HTTP header to authenticate to the HDFS WebHDFS URL and Oozie REST API URL.
I referenced the url below to have the below code to generate the Negotiate token.
https://www.ibm.com/support/knowledgecenter/en/SS7JFU_8.5.5/com.ibm.websphere.express.doc/ae/tsec_SPNEGO_token.html
public class TokenCreation {
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
private static final String KERBEROS_OID = "1.2.840.113554.1.2.2";
public static byte[] genToken(String principal) {
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
byte[] spnegoToken = new byte[0];
try {
Oid spnegoMechOid = new Oid(SPNEGO_OID);
Oid krb5MechOid = new Oid(KERBEROS_OID);
GSSCredential clientGssCreds = null;
GSSManager manager = GSSManager.getInstance();
GSSName gssUserName = manager.createName(principal, GSSName.NT_USER_NAME, krb5MechOid);
clientGssCreds = manager.createCredential(gssUserName.canonicalize(krb5MechOid),
GSSCredential.INDEFINITE_LIFETIME,
krb5MechOid,
GSSCredential.INITIATE_ONLY);
clientGssCreds.add(gssUserName,
GSSCredential.INDEFINITE_LIFETIME,
GSSCredential.INDEFINITE_LIFETIME,
spnegoMechOid, GSSCredential.INITIATE_ONLY);
GSSName gssServerName = manager.createName(principal, GSSName.NT_USER_NAME);
GSSContext clientContext = manager.createContext(gssServerName.canonicalize(spnegoMechOid),
spnegoMechOid,
clientGssCreds,
GSSContext.DEFAULT_LIFETIME);
// optional enable GSS credential delegation
clientContext.requestCredDeleg(true);
// create a SPNEGO token for the target server
spnegoToken = clientContext.initSecContext(spnegoToken, 0, spnegoToken.length);
} catch (GSSException e) {
e.printStackTrace();
}
return spnegoToken;
}
But after running the above code, I always got the below prompt:
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.c.u.security.KrbUtils - after loginUserFromKeytab............AtoimcUser:HTTP/host1.exmaple.com#EXAMPLE.COM
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.app.oozie.OozieAppCaller - ->>>>>>User Name is HTTP/host1.exmaple.com#EXAMPLE.COM
2019-09-25 14:12:51 760 [INFO] [pool-2-thread-1] c.s.n.app.oozie.OozieAppCaller - ->>>>>>Mode is KERBEROS
>>>KinitOptions cache name is /tmp/krb5cc_0
Kerberos username [root]: ^C^C^C
Kerberos password for root:
You can see at the end of the above output log.
The "Kerberos username" is always prompt to ask for username.
Also I have tried to manually run kinit the keytab.
and the above class can generate the token successfully.
But manually run kinit is NOT the way I wanted.
Would you please help it?
Thanks.
Kerberos and SPNEGO support in Java is cumbersome unfortunately.
I've created a small library to simplify some Kerberos use cases: https://github.com/bedrin/kerb4j
You can use it like this to generate SPNEGO token:
SpnegoClient spnegoClient = SpnegoClient.loginWithKeyTab("svc_consumer", "/opt/myapp/consumer.keytab");
URL url = new URL("http://api.provider.acme.com/api/operation1");
SpnegoContext context = spnegoClient.createContext("http://provider.acme.com"); // Will result in HTTP/provider.acme.com SPN
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", context.createTokenAsAuthroizationHeader());

How to get al alias from hsm by SUNPKCS provider?

I want to get my all key aliases from hsm, but i get this error message :
Exception in thread "main" java.io.IOException: load failed
at sun.security.pkcs11.P11KeyStore.engineLoad(P11KeyStore.java:778)
at java.security.KeyStore.load(KeyStore.java:1445)
at eracom.provider.ProCrypt.main(ProCrypt.java:99)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception:
CKR_OBJECT_HANDLE_INVALID
at sun.security.pkcs11.wrapper.PKCS11.C_GetAttributeValue(Native Method)
at sun.security.pkcs11.P11KeyStore.mapLabels(P11KeyStore.java:2415)
at sun.security.pkcs11.P11KeyStore.engineLoad(P11KeyStore.java:770)
If i create just one secret key on hsm. there is no problem, i can get
the alia from hsm, but if i have 2 or more, i get the error.
How to solve it?
KeyStore keyStore = KeyStore.getInstance("PKCS11", pkcs11);
keyStore.load(null, slotPIN);
SecretKey key = (SecretKey) keyStore.getKey("KEY2", slotPIN);
System.out.println("key's attributes: " + key.toString());
java.util.Enumeration<String> aliases = keyStore.aliases();
String alias = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
System.out.println("key label name : " + alias);
}

Trouble connecting to SSL enabled mongo cluster from Spark Application

I'm trying to connect to a SSL enabled mongo cluster from a spark application. I'm trying to use self signed cert and getting the following error.
Exception in monitor thread while connecting to server CLUSTER_NAME
com.mongodb.MongoSocketWriteException: Exception sending message
at com.mongodb.internal.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:525)
at com.mongodb.internal.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:413)
at com.mongodb.internal.connection.InternalStreamConnection.sendCommandMessage(InternalStreamConnection.java:269)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:253)
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:106)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:63)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching CLUSTER_NAME found
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
My read config uri looks something like this:
val uri: String = "mongodb://" + URLEncoder.encode(Login, "UTF-8") + ":" + URLEncoder.encode(Password, "UTF-8") + "#" + cluster + ":27017/" + database + "." + collection + "?authSource=" + (if (authenticationDatabase != "") authenticationDatabase else "admin") + (if (replicaset == null) "" else "&replicaSet=" + replicaset) + "&ssl=true"
I want to use self signed cert something like :
class TrustAllX509TrustManager extends X509TrustManager {
override def getAcceptedIssuers = new Array[X509Certificate](0)
override def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {
}
override def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {
}
}
The version of the env's I'm using:
Spark: 2.2.0
Mongo: 3.4
Any help will be appreciated.
Thanks!
This is same as making any other SSL connection. Import your cert in keystore and refer to that key store using below code
System.setProperty("javax.net.ssl.trustStore", "keystoreFilefullpath")
System.setProperty("javax.net.ssl.trustStorePassword", "password")
Once these params are set then Kafka SSL should work. If you are publishing from Spark then keystore file must be uploaded to driver/executor using --files option

javax.security.sasl.SaslException: Authentication failed: the server presented no authentication mechanisms in Wildfly 10.1

I am new to EJBs, and I am trying to perform remote invocations on stateless and stateful beans that I have deployed on a pod in my project that is based on Wildfly 10.1 in the new OpenShift 3 (Origin). The code that I am using for initializing the client context looks like:
Properties clientProperties = new Properties();
clientProperties.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
clientProperties.put("remote.connections", "default");
clientProperties.put("remote.connection.default.host", "localhost");
clientProperties.put("remote.connection.default.port", "8080");
clientProperties.put("remote.connection.default.username", "****");
clientProperties.put("remote.connection.default.password", "****"); clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "false");
clientProperties.put("remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
EJBClientContext.setSelector(new ConfigBasedEJBClientContextSelector(new
PropertiesBasedEJBClientConfiguration(clientProperties)));
Properties contextProperties = new Properties();
contextProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
contextProperties.put(Context.SECURITY_PRINCIPAL, "****"); //username
contextProperties.put(Context.SECURITY_CREDENTIALS, "****"); //password
Context context = new InitialContext(contextProperties);
String appName = "CloudEAR";
String moduleName = "CloudEjb";
String distinctName = "";
String beanName = "Calculator";
String qualifiedRemoteView = "cloudEJB.view.CalculatorRemote";
String lookupString = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + qualifiedRemoteView;
Calculator calculator = (CalculatorRemote) context.lookup(lookupString);
int sum = calculator.sum(10, 10);
And the error message that I get is:
WARN: Could not register a EJB receiver for connection to localhost:8080
javax.security.sasl.SaslException: Authentication failed: the server presented no authentication mechanisms
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:378)
at org.jboss.remoting3.remote.ClientConnectionOpenListener$Capabilities.handleEvent(ClientConnectionOpenListener.java:240)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.channels.TranslatingSuspendableChannel.handleReadable(TranslatingSuspendableChannel.java:198)
at org.xnio.channels.TranslatingSuspendableChannel$1.handleEvent(TranslatingSuspendableChannel.java:112)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.ChannelListeners$DelegatingChannelListener.handleEvent(ChannelListeners.java:1092)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:89)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:567)
at ...asynchronous invocation...(Unknown Source)
at org.jboss.remoting3.EndpointImpl.doConnect(EndpointImpl.java:272)
at org.jboss.remoting3.EndpointImpl.connect(EndpointImpl.java:388)
Initially I tried using the "jboss-ejb-client.properties" file, but that wasn't even able to make the remote connection. Now I am manually creating and configuring the EJBClientContext, and at least is successfully connecting to the remote server, but the invocation filas because of authentication failures.
I remember that we used to solve this issue by removing the "security realm" argument in "standalone.xml" files in older versions of OpenShift; however I am not able to find that file in the new version anymore. I have been looking at concepts such as secrets, volumes etc. but I really don't have a clear understanding how this works. When I create a new secret and try to associate it with my pod, the new deployment procedure fails. I would really appreciate any help.

Exception - Client not found in Kerberos database (6) with spnego-Kerberos IWA

I am getting following error for SPNEGO/Kerberos Authentication
I get this error when I run HelloKeyTab.java file.
***Exception in thread "main" javax.security.auth.login.LoginException: Client not
found in Kerberos database (6)**
at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(K
b5LoginModule.java:763)
at com.sun.security.auth.module.Krb5LoginModule.login(Krb5LoginModule.j
va:584)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl
java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcce
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:762)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:
03)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:690)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:
87)
at javax.security.auth.login.LoginContext.login(LoginContext.java:595)
at net.sourceforge.spnego.SpnegoHttpURLConnection.<init>(SpnegoHttpURLC
nnection.java:207)
at HelloKeytab.main(HelloKeytab.java:17)
Caused by: KrbException: Client not found in Kerberos database (6)
at sun.security.krb5.KrbAsRep.<init>(KrbAsRep.java:76)
at sun.security.krb5.KrbAsReqBuilder.send(KrbAsReqBuilder.java:319)
at sun.security.krb5.KrbAsReqBuilder.action(KrbAsReqBuilder.java:364)
at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(K
b5LoginModule.java:735)
... 14 more
Caused by: KrbException: Identifier doesn't match expected value (906)
at sun.security.krb5.internal.KDCRep.init(KDCRep.java:143)
at sun.security.krb5.internal.ASRep.init(ASRep.java:65)
at sun.security.krb5.internal.ASRep.<init>(ASRep.java:60)
at sun.security.krb5.KrbAsRep.<init>(KrbAsRep.java:60)
... 17 more*
Setup,link and files I have used for SPNEGO/Kerberos Authentication.
link- http://spnego.sourceforge.net/
Domain account for tomcat server
user - xyztest
password - ****
principal - princ HTTP/APPSERVER1#corp.xyz.com
1)HelloKeyTab.java - Test keytab generated for apache tomcat server
public class HelloKeytab {
public static void main(final String[] args) throws Exception {
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", "login.conf");
SpnegoHttpURLConnection spnego = null;
try {
System.out.println("11111111");
spnego = new SpnegoHttpURLConnection("custom-client");
spnego.connect(new URL("http://localhost:8080/DemoAuth/hello_spnego.jsp"));
System.out.println("2222222");
System.out.println("HTTP Status Code: "
+ spnego.getResponseCode());
System.out.println("HTTP Status Message: "
+ spnego.getResponseMessage());
} finally {
if (null != spnego) {
spnego.disconnect();
}
}
}
}
2)krb5.conf - Kerberos Configuration File
[libdefaults]
default_tkt_enctypes = aes256-cts aes256-cts-hmac-sha1-96 aes128-cts- hmac-sha1-96 aes128-cts rc4-hmac des3-cbc-sha1 des-cbc-md5 des-cbc-crc arcfour-hmac arcfour-hmac-md5
default_tgt_enctypes = aes256-cts aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 aes128-cts rc4-hmac des3-cbc-sha1 des-cbc-md5 des-cbc-crc arcfour-hmac arcfour-hmac-md5
permitted_enctypes = aes256-cts aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 aes128-cts rc4-hmac des3-cbc-sha1 des-cbc-md5 des-cbc-crc arcfour-hmac arcfour-hmac-md5
default_domain = CORP.XYZ.COM
[realms]
CORP.XYZ.COM = {
kdc = CORP.XYZ.COM
default_domain = CORP.XYZ.COM
}
[domain_realm]
CORP.XYZ.COM = CORP.XYZ.COM
3)login.conf -Login configuration file
custom-client {
com.sun.security.auth.module.Krb5LoginModule required
storeKey=true
useKeyTab=true
keyTab="C:/apache-tomcat-7.0.40-windows-x64/apache-tomcat-7.0.40/bin/xyztest.keytab"
principal="HTTP/APPSERVER1#corp.xyz.com";
};
spnego-client {
com.sun.security.auth.module.Krb5LoginModule required;
};
spnego-server {
com.sun.security.auth.module.Krb5LoginModule required
storeKey=true
useKeyTab=true
keyTab="C:/apache-tomcat-7.0.40-windows-x64/apache-tomcat-7.0.40/bin/xyztest.keytab"
principal="HTTP/APPSERVER1#corp.xyz.com";
};
4)setspn command -to register principal
setspn -s HTTP/APPSERVER1 xyztest
Checking domain DC=corp,DC=xyz,DC=com
Registering ServicePrincipalNames for CN=xyztest,CN=Users,DC=corp,DC=xyz,DC=com
HTTP/APPSERVER1
Updated object
PS C:\Windows\system32> setspn -s HTTP/APPSERVER1.corp.xyz.com xyztest
Checking domain DC=corp,DC=xyz,DC=com
Registering ServicePrincipalNames for CN=xyztest,CN=Users,DC=corp,DC=xyz,DC=com
HTTP/APPSERVER1.corp.xyz.com
Updated object
5)ktpass command : to generate keytab file
ktpass /princ HTTP/APPSERVER1#corp.xyz.com /mapuser xyztest /pass ***** /out xyztest.keytab /crypto AES256-SHA1 /ptype KRB5_NT_PRINCIPAL
Targeting domain controller: xyzDC1.corp.xyz.com
Using legacy password setting method
ktpass : Successfully mapped HTTP/APPSERVER1 to xyztest.
At line:1 char:1
+ ktpass /princ HTTP/APPSERVER1#corp.xyz.com /mapuser xyztest /pass *****
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Successfully ma...o xyztest.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Key created.
Output keytab to xyztest.keytab:
Keytab version: 0x502
keysize 84 HTTP/APPSERVER1#corp.xyz.com ptype 1 (KRB5_NT_PRINCIPAL) vno 3 etype 0x12 (AES256-SHA1) keylength 32
(0x6e6afbbefc78946121bd7ed6657524c7409917cae1708223ce938449113d9805)
6)Apache tomcat server
7)JDK 7
8)Domain Controller - Windows Active directory
9)If I try to run kinit command to authenticate principal with keytab I get the same error Client not found in Kerberos database (6)
Command - kinit -k -t xyztest.keytab HTTP/APPSERVER1#corp.xyz.com
Result - Exception krb_error 6 client not found in kerberos database (6)
10)HelloKDC.java : Link http://spnego.sourceforge.net/ provides HelloKDC.java to test connection to KDC. I can successfully connect to the KDC with HelloKDC.java
public final class HelloKDC {
private HelloKDC() {
// default private
}
public static void main(final String[] args) throws Exception {
// Domain (pre-authentication) account
final String username = "xyztest";
// Password for the pre-auth acct.
final String password = "!Dragonfly1!";
// Name of our krb5 config file
final String krbfile = "krb5.conf";
// Name of our login config file
final String loginfile = "login.conf";
// Name of our login module
final String module = "spnego-client";
// set some system properties
System.setProperty("java.security.krb5.conf", krbfile);
System.setProperty("java.security.auth.login.config", loginfile);
//System.setProperty("sun.security.krb5.debug", true);
// assert
HelloKDC.validate(username, password, krbfile, loginfile, module);
final CallbackHandler handler =
HelloKDC.getUsernamePasswordHandler(username, password);
final LoginContext loginContext = new LoginContext(module, handler);
// attempt to login
loginContext.login();
// output some info
System.out.println("Subject=" + loginContext.getSubject());
// logout
loginContext.logout();
System.out.println("Connection test successful.");
}
private static void validate(final String username, final String password
, final String krbfile, final String loginfile, final String moduleName)
throws FileNotFoundException, NoSuchAlgorithmException {
// confirm username was provided
if (null == username || username.isEmpty()) {
throw new IllegalArgumentException("Must provide a username");
}
// confirm password was provided
if (null == password || password.isEmpty()) {
throw new IllegalArgumentException("Must provide a password");
}
// confirm krb5.conf file exists
if (null == krbfile || krbfile.isEmpty()) {
throw new IllegalArgumentException("Must provide a krb5 file");
} else {
final File file = new File(krbfile);
if (!file.exists()) {
throw new FileNotFoundException(krbfile);
}
}
// confirm loginfile
if (null == loginfile || loginfile.isEmpty()) {
throw new IllegalArgumentException("Must provide a login file");
} else {
final File file = new File(loginfile);
if (!file.exists()) {
throw new FileNotFoundException(loginfile);
}
}
// confirm that runtime loaded the login file
final Configuration config = Configuration.getConfiguration();
// confirm that the module name exists in the file
if (null == config.getAppConfigurationEntry(moduleName)) {
throw new IllegalArgumentException("The module name "
+ moduleName + " was not found in the login file");
}
}
private static CallbackHandler getUsernamePasswordHandler(
final String username, final String password) {
final CallbackHandler handler = new CallbackHandler() {
public void handle(final Callback[] callback) {
for (int i=0; i<callback.length; i++) {
if (callback[i] instanceof NameCallback) {
final NameCallback nameCallback = (NameCallback) callback[i];
nameCallback.setName(username);
} else if (callback[i] instanceof PasswordCallback) {
final PasswordCallback passCallback = (PasswordCallback) callback[i];
passCallback.setPassword(password.toCharArray());
} else {
System.err.println("Unsupported Callback: "
+ callback[i].getClass().getName());
}
}
}
};
return handler;
}
}
Please provide me solution to resolve the error
Client not found in Kerberos database (6)
klist output
#0> Client: xyztest # CORP.XYZ.COM
Server: krbtgt/CORP.XYZ.COM # CORP.XYZ.COM
KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
Ticket Flags 0x60a10000 -> forwardable forwarded renewable pre_authent n
ame_canonicalize
Start Time: 3/8/2017 10:01:14 (local)
End Time: 3/8/2017 20:01:14 (local)
Renew Time: 3/15/2017 10:01:14 (local)
Session Key Type: AES-256-CTS-HMAC-SHA1-96
Cache Flags: 0x2 -> DELEGATION
Kdc Called: xyzDC1.corp.xyz.com
#1> Client: xyztest # CORP.XYZ.COM
Server: krbtgt/CORP.XYZ.COM # CORP.XYZ.COM
KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
Ticket Flags 0x40e10000 -> forwardable renewable initial pre_authent nam
e_canonicalize
Start Time: 3/8/2017 10:01:14 (local)
End Time: 3/8/2017 20:01:14 (local)
Renew Time: 3/15/2017 10:01:14 (local)
Session Key Type: AES-256-CTS-HMAC-SHA1-96
Cache Flags: 0x1 -> PRIMARY
Kdc Called: xyzDC1.corp.xyz.com
#2> Client: xyztest # CORP.XYZ.COM
Server: ldap/xyzDC1.corp.xyz.com # CORP.XYZ.COM
KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_deleg
ate name_canonicalize
Start Time: 3/8/2017 10:01:16 (local)
End Time: 3/8/2017 20:01:14 (local)
Renew Time: 3/15/2017 10:01:14 (local)
Session Key Type: AES-256-CTS-HMAC-SHA1-96
Cache Flags: 0
Kdc Called: xyzDC1.corp.xyz.com
#3> Client: xyztest # CORP.XYZ.COM
Server: LDAP/xyzDC1.corp.xyz.com/corp.xyz.com # CORP.ADAP
TIVE.COM
KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_deleg
ate name_canonicalize
Start Time: 3/8/2017 10:01:15 (local)
End Time: 3/8/2017 20:01:14 (local)
Renew Time: 3/15/2017 10:01:14 (local)
Session Key Type: AES-256-CTS-HMAC-SHA1-96
Cache Flags: 0
Kdc Called: xyzDC1.corp.xyz.com
#4> Client: xyztest # CORP.XYZ.COM
Server: cifs/xyzDC1.corp.xyz.com # CORP.XYZ.COM
KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_deleg
ate name_canonicalize
Start Time: 3/8/2017 10:01:14 (local)
End Time: 3/8/2017 20:01:14 (local)
Renew Time: 3/15/2017 10:01:14 (local)
Session Key Type: AES-256-CTS-HMAC-SHA1-96
Cache Flags: 0
Kdc Called: xyzDC1.corp.xyz.com
Keep the below things in mind when working on Kerberos Environment
Realm (Domain Name) should be in UPPER CASE when creating keytab file as well as wherever you are using Realm
For SPNEGO authentication, each server host should be mapped as HTTP/hostname for the web authentication user. For example,
setspn -s HTTP/hostname xyztest
Kerberos ticket should be available in the environment krb5ccname for each operation
To get Kerberos ticket using username and password
kinit principal password
To get Kerberos ticket using keytab
kinit -k -t keytab principal
You can set ticket location using environment variable krb5ccname
set krb5ccname=newticketfilelocation
To list the ticket details, change directory to java\bin and run klist. This is because klist command is available in windows and it shows only logged in user tickets. To list the ticket got from kinit command, you should run from java\bin location
klist