java通过kerberos认证并通过GSS-API获取kerberos服务票证
- @Component
- public class EsKerberosUtils {
- //主体用户
- @Value("${kerberos.principal}")
- private String kPrincipal;
-
- @Value("${java.security.krb5.realm}")
- private String jRealm;
-
- //kdc服务ip
- @Value("${java.security.krb5.kdc}")
- private String kdc;
-
- @Value("${kerberos.keytab}")
- private String keytab;
-
- public String getToken(){
-
- String kb = System.getProperty("user.dir")+ File.separator+"kerberos"+ File.separator+keytab;
-
- System.setProperty("java.security.krb5.realm", jRealm);
- System.setProperty("java.security.krb5.kdc", kdc);
-
- javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() {
- @Override
- public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
- HashMap<String, Object> options = new HashMap<String, Object>() {
- {
- put("useKeyTab", "true");
- put("keyTab", kb);
- put("principal", kPrincipal);
- put("doNotPrompt", "true");
- put("storeKey", "true");
- put("isInitiator", "true");
- put("debug", "false");
- }
- };
- return new AppConfigurationEntry[]{
- new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)
- };
- }
- };
-
- Set<Principal> princ = new HashSet<Principal>(1);
-
- princ.add(new KerberosPrincipal(kPrincipal));
- Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
- LoginContext lc = null;
- try {
- lc = new LoginContext("Krb5Login", sub, null, config);
- lc.login();
- Subject serviceSubject = lc.getSubject();
- final Base64 base64 = new Base64(0);
-
- String token = Subject.doAs(serviceSubject, new PrivilegedExceptionAction<String>() {
- final Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
- final Oid krb5MechOid = new Oid("1.2.840.113554.1.2.2");
-
- @Override
- public String run() throws Exception {
-
- GSSContext gssContext = null;
-
- GSSManager gssManager = GSSManager.getInstance();
-
- try {
- GSSName gssServerName = gssManager.createName(kPrincipal, GSSName.NT_USER_NAME);
- GSSCredential clientGssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME,
- krb5MechOid, GSSCredential.INITIATE_ONLY);
- gssContext = gssManager.createContext(gssServerName.canonicalize(spnegoOid),
- spnegoOid,
- clientGssCreds,
- GSSContext.DEFAULT_LIFETIME);
- gssContext.requestCredDeleg(true);
-
- byte[] spnegoToken = new byte[0];
- spnegoToken = gssContext.initSecContext(spnegoToken, 0, spnegoToken.length);
- byte[] encodedToken = Base64.encodeBase64(spnegoToken);
- return new String(encodedToken, "UTF-8");
- } finally {
- if (gssContext != null) {
- gssContext.dispose();
- }
- }
- }
- });
-
- return token;
-
- } catch (LoginException e) {
- e.printStackTrace();
- } catch (PrivilegedActionException e) {
- e.printStackTrace();
- } catch (GSSException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
- }
- }