基于kerberos实现jaas登录

这段时间在做hadoop和kerberos的整合,顺便看了jaas和kerberos,这里给出使用kerberos登录模块的jaas例子。

前提条件

1.kerberos已经安装,principal已经创建,这里用的principal是已经建好的nn/[email protected];

2.客户端配置了kerberos;

3.在JDK_HOME\jre\lib\security\java.security中增加配置项:

auth.login.defaultCallbackHandler=com.sun.security.auth.callback.TextCallbackHandler

代码示例

示例涉及两个java类,一个是kerberos的配置类Krb5Configuration,一个是客户端类KerberosClient。运行代码KerberosClient就可以看效果了。

package security;

import java.io.File;

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

public class KerberosClient {

	public static void main(String[] args) {
		String loginModuleName = "KerberosLogin";
		Subject subject = new Subject();
		Krb5Configuration conf = new Krb5Configuration();
		try {
			String sep = File.separator;
			System.out.println("KerberosClient.main():"
					+ System.getProperty("java.home") + sep + "lib" + sep
					+ "security" + sep + "java.security");
			LoginContext context = new LoginContext("myKerberosLogin", subject,
					null, conf);
			context.login();
			System.out.println(context.getSubject().getPrincipals());
			
		} catch (LoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

 

package security;

import java.util.HashMap;
import java.util.Map;

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

public class Krb5Configuration extends Configuration{

	private AppConfigurationEntry[] entry = new AppConfigurationEntry[1];
	
	Map paramMap = new HashMap();
	
	private AppConfigurationEntry krb5LoginModule = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", LoginModuleControlFlag.REQUIRED, paramMap);
	@Override
	public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
		if(entry[0] == null){
			paramMap.put("debug", "true");
			
			//1.enter the username and passsword 
			//paramMap.put("storeKey", "true");
			//paramMap.put("doNotPrompt", "false");
			
			//2.use keytab file
			paramMap.put("doNotPrompt", "true");
			paramMap.put("useKeyTab", "true");
			paramMap.put("keyTab", "/hadoop-data/etc/hadoop/nn.service.keytab");
			paramMap.put("principal", "nn/[email protected]");
			
			paramMap.put("useTicketCache", "true");
			paramMap.put("ticketCache", "/hadoop-data/etc/hadoop/keytab_cache");
			
			
			entry[0] = krb5LoginModule;
		}
		return entry;
	}

}


你可能感兴趣的:(example,jaas,kerberos,示例代码)