java – 使用jdbc和Kerberos委派连接到SAP HANA数据库

是否可以使用jdbc和Kerberos委派从我的
Java应用程序连接到SAP HANA DB?

现在我可以创建与SAP HANA DB的jdbc连接,而无需输入db登录名和密码,只使​​用windows登录.
为此,我在SAP HANA管理控制台(user1 @ domain_name)中为db用户设置Kerberos外部ID,并在创建jdbc连接时使用属性“NativeAuthentification = true”.
然后我通过user1登录Windows并运行我的应用程序,我可以连接到SAP HANA DB并选择数据.

但我需要在客户端计算机上登录Windows,运行我的客户端Java应用程序,连接到我的应用程序服务器,应用程序服务器必须连接到具有已连接用户权限的SAP HANA数据库并选择数据,授予此用户.

在客户端java应用程序中,我使用waffle-jna库获取了kerberos令牌,然后我使用它连接到使用Spring Security的应用程序服务器(它可以工作),但是我无法使用此令牌创建到SAP HANA DB的jdbc连接.我不能使用Kerberos委派.

有没有人通过jdbc了解SAP HANA DB中的Kerberos委派?谢谢.

最佳答案 我使用GSS API解决了这个问题.现在我简要介绍一下在我的环境中工作的设置和代码

1.环境

客户端java应用程序在Windows 7上运行(java SE版本8,swing),在Windows 2012上运行的应用程序服务器r2(java 8,tomcat或者jetty,在glassfish上运行不起作用),sap hana db在linux上运行.
Windows用户将连接到运行应用程序服务器的hana db和Windows用户,它位于一个Windows域(活动目录)中.

2.配置Windows域

在Windows域控制器中创建了spn和.keytab文件

3.配置hana

有很好的指南“HowTo_HANA_SSO_Kerberos_v1.7.1.pdf”
是否在hana中使用外部ID用户@winddomain创建了db用户(来自windows活动目录的帐户名)
有一个很好的python脚本,用于配置hana for kerberos和check配置.我们通过sap hana支持网站获得了这个脚本.

4.客户端配置

必须将windows注册表项allowtgtsessionkey设置为true

客户端是文件
login.conf的

com.sun.security.jgss.login {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=true
doNotPrompt=true
debug=true;
};

com.sun.security.jgss.initiate {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=true 
principal="saphanauser"
debug=true;
};

和krb5.conf

[libdefaults]
    default_realm = DOMAINNAME.NEW
    forwardable = true
    clockskew = 3000
    default_tkt_enctypes = aes256-cts aes128-cts rc4-hmac
    default_tgs_enctypes = aes256-cts aes128-cts rc4-hmac
    permitted_enctypes  = aes256-cts aes128-cts rc4-hmac
[realms]
        DOMAINNAME.NEW = {
                kdc = KDCSERVERNAME
        default_domain = DOMAINNAME.NEW
        }
[domain_realm]
        .domainname.new = DOMAINNAME.NEW
        domainname.new = DOMAINNAME.NEW

5.服务器配置

在服务器上是文件

login.conf的

com.sun.security.jgss.login {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=true
doNotPrompt=true
debug=true;
};

com.sun.security.jgss.initiate {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=true 
debug=true;
};

com.sun.security.jgss.accept {
com.sun.security.auth.module.Krb5LoginModule required
storeKey=true
keyTab="C:/krb/keytab/krb5_hdb.keytab"
useKeyTab=true
realm="DOMAINNAME.NEW"
principal="HDB/LINUX.DOMAINNAME.NEW"
isInitiator=false
debug=true;
};

和krb5.conf

[libdefaults]
    default_realm = DOMAINNAME.NEW
    forwardable = true
    default_tkt_enctypes = aes256-cts aes128-cts rc4-hmac
    default_tgs_enctypes = aes256-cts aes128-cts rc4-hmac
    permitted_enctypes  = aes256-cts aes128-cts rc4-hmac
[realms]
        DOMAINNAME.NEW = {
                kdc = KDCSERVERNAME
        default_domain = DOMAINNAME.NEW
        }

[domain_realm]
        .domainname.new = DOMAINNAME.NEW
        domainname.new = DOMAINNAME.NEW

6.客户代码

获取令牌以将其发送到应用程序服务器

public static byte[] getTokenGss() throws GSSException {

        String spnName = "spn_name";

        String oidValue= "1.2.840.113554.1.2.2"; // KERBEROS_MECH_OID
        String userLogin = System.getProperty("user.name");
        Oid mechOid = new Oid(oidValue);

        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

        Path directoryConf = "C:\\client\\krb";
        String pathToGssConfigFile = directoryConf.resolve("login.conf").toString();
        System.setProperty("java.security.auth.login.config", pathToGssConfigFile);
        String pathToKrb5ConfigFile = directoryConf.resolve("krb5.conf").toString();
        System.setProperty("java.security.krb5.conf", pathToKrb5ConfigFile);

        System.setProperty("sun.security.krb5.debug", "true");

        GSSManager manager = GSSManager.getInstance();
        GSSName gssUserName = manager.createName(userLogin, GSSName.NT_USER_NAME, mechOid);

        logger.debug("before createCredential");
        GSSCredential clientGssCreds =
                manager.createCredential(gssUserName.canonicalize(mechOid), GSSCredential.INDEFINITE_LIFETIME, mechOid,
                                         GSSCredential.INITIATE_ONLY);

        byte[] token = new byte[0];

        // create target server SPN
        GSSName gssServerName = manager.createName(spnName, GSSName.NT_USER_NAME);
        logger.debug("before createContext");

        GSSContext clientContext = manager.createContext(gssServerName.canonicalize(mechOid), mechOid, clientGssCreds,
                                                         GSSContext.DEFAULT_LIFETIME);

        // optional enable GSS credential delegation
        clientContext.requestCredDeleg(true);
        token = clientContext.initSecContext(token, 0, token.length);
        return token;

    }

7.服务器代码

使用来自客户端的令牌创建hibernate EntityManagerFactory

private EntityManagerFactory createEntNamagerFactoryViaKerberos(byte[] inToken)
            throws Exception {

        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
        System.setProperty("java.security.auth.login.config", "C:\\krb\\gsslogin\\login.conf");
        System.setProperty("java.security.krb5.conf", "C:\\krb\\krb5.conf");

        Oid mechOid = new Oid("1.2.840.113554.1.2.2");
        GSSManager manager = GSSManager.getInstance();

        //first obtain it's own credentials...
        GSSCredential myCred =
                manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, mechOid, GSSCredential.ACCEPT_ONLY);

        //...and create a context for this credentials...
        GSSContext context = manager.createContext(myCred);

        //...then use that context to authenticate the calling peer by reading his token
        byte[] tokenForPeer = context.acceptSecContext(inToken, 0, inToken.length);

        if (!context.isEstablished()) {
            throw new Exception("Context not established!");
        }

        //...then obtain information from the context
        logger.debug("Clientcipal is " + context.getSrcName());
        logger.debug("Servercipal is " + context.getTargName());

        if (context.getCredDelegState()) {
            logger.debug("Then is delegatable.");
        } else {
            logger.debug("Then is NOT delegatable");
        }

        GSSCredential clientCr = context.getDelegCred();
        Subject s = GSSUtil.createSubject(clientCr.getName(), clientCr);
        KerberosActionCreateEmf kerberosAction = new KerberosActionCreateEmf();
        kerberosAction.unicalEntFactoryName = "kerb" + System.currentTimeMillis();
        Subject.doAs(s, kerberosAction);
        EntityManagerFactory emf = kerberosAction.emf;
        return emf;

    }



    class KerberosActionCreateEmf implements PrivilegedExceptionAction {

        public EntityManagerFactory emf;

        public String modelName;
        public String unicalEntFactoryName;

        @Override
        public Object run() throws Exception {

            Properties properties = new Properties();
            properties.setProperty("javax.persistence.jdbc.driver", "com.sap.db.jdbc.Driver");
            properties.setProperty("hibernate.connection.url", "jdbc:sap://10.0.0.121:31015");
            properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HANAColumnStoreDialect");

            // do not use login and pass, use kerberos delegation (token)
            //properties.setProperty("hibernate.connection.username", login);
            //properties.setProperty("hibernate.connection.password", pass);

            properties.setProperty("hibernate.default_schema", "default_schema");
            properties.setProperty("hibernate.show_sql", model_manager_hibernate_show_sql);
            properties.setProperty("hibernate.ejb.entitymanager_factory_name", unicalEntFactoryName);
            properties.setProperty("hibernate.cache.use_query_cache", "false");
            properties.setProperty("hibernate.query.plan_cache_max_soft_references", "1");
            properties.setProperty("hibernate.query.plan_cache_max_strong_references", "1");

            properties.setProperty("hibernate.hikari.minimumIdle", "3");
            properties.setProperty("hibernate.hikari.maximumPoolSize", "20");
            properties.setProperty("hibernate.hikari.idleTimeout", "600000");
            properties.setProperty("hibernate.hikari.AutoCommit", "false");
            properties.setProperty("hibernate.hikari.poolName", unicalEntFactoryName);
            properties.setProperty("hibernate.hikari.connectionTimeout", "1800000");

            EntityManagerFactory newEntityManagerFactory =
                    Persistence.createEntityManagerFactory("persistenceUnitName", properties);

            emf = newEntityManagerFactory;
            return null;
        }
    }

8.有用的链接

http://thejavamonkey.blogspot.com/2008/04/clientserver-hello-world-in-kerberos.html
https://dmdaa.wordpress.com/category/java/jgss/
https://dmdaa.wordpress.com/2010/03/13/kerberos-setup-and-jaas-configuration-for-running-sun-jgss-tutorial-against-ad/
http://cr.openjdk.java.net/~weijun/special/krb5winguide-2/raw_files/new/kwin

点赞