MongoDB 配置Kerberos 认证,并用JAVA连接

Kerberos(KDC) 几个重要的概念:

  • Principal:任何服务器所提供的用户、计算机、服务都将被定义成Principal。本例使用[email protected]
  • Instances:用于服务principals和特殊管理Principal。
  • Realms:Kerberos安装提供的独特的域的控制,把它想象成你的主机和用户所属的主机或者组。官方约定这域需要大写。默认的,Ubuntu将把DNS域名转换为大写当成这里的域。 本例使用EXAMPLE.COM
  • Key Distribution Center: (KDC)由三部分组成,一是principal数据库,认证服务器,和票据授予服务器。每个Realm至少要有一个。
  • Ticket Granting Ticket:由认证服务器(AS)签发,Ticket Granting Ticket (TGT)使用用户的密码加密,这个密码只有用户和KDC知道。
  • Ticket Granting Server: (TGS) 根据请求签发服务的票据。
  • Tickets:确认两个Principal的身份。一个主体是用户,另一个是由用户请求的服务。门票会建立一个加密密钥,用于在身份验证会话中的安全通信。
  • Keytab Files:从KDC主数据库中提取的文件,并且包含的服务或主机的加密密钥。

Kerberos 用户和服务认证的流程

精品电影网:手机电影迅雷下载,手机在线电影,手机高清电影,手机迅雷观看,电影天堂

1,客户端(像MongoDB java 驱动程序)向KDC服务器发送一个principal。
2,服务器在自己的数据库中查找到这个用户并用这个用户的秘钥(注意不是秘密)和当前时间戳加密生成一个TGT返回给客户端。
3,客户端用这个TGT打包要连接的服务名和服务相关信息再发送给KDC。
4,KDC验证这个新TGT包并用服务的秘钥和新的时间戳加密一个新的TGT返回给客户端。
5,客户端拿到新的TGT发送给服务service(本例中的MongoDB)
6,服务service(MongoDB用自己的私钥进行解密TGT并验证),如果验证成功则返回给客户端想要的数据。

安装Kerberos (KDC) 服务

sudo apt install krb5-kdc krb5-admin-server
sudo krb5_newrealm
所有的配置都在/etc/krb5.conf中,可以更改这个文件后运行下面的命令
sudo dpkg-reconfigure krb5-kdc

增加一个管理员用户principle

sudo kadmin.local
Authenticating as principal root/[email protected] with password.
kadmin.local: addprinc user

然后输入这个用户的密码,这个用户就加到kerberos中了。
在 /etc/krb5kdc/kadm5.acl 中增加这个管理员用户: [email protected] 

然后重启kerberos:
 sudo service krb5-admin-server restart

测试用这个用户连接下看是否成功:
kinit  [email protected] 

增加一个kerberos权限的mongo用户principal 和 mongodb服务principal

在kerberos服务器机器上运行:
kadmin.local

- 增加用户并设置密码
addprinc [email protected]
listprincs

- 增加mongdb服务并设置密码
 addprinc mongodb/[email protected]
 addprinc mongod/[email protected]
 addprinc mongos/[email protected]
 addprinc mongo/[email protected]

导出keytab文件到指定目录
ktadd -k /home/jpmovie/user1.keytab -norandkey [email protected]
ktadd -k /home/jpmovie/mongodb.keytab -norandkey mongodb/[email protected]
ktadd -k /home/jpmovie/mongod.keytab -norandkey mongod/[email protected]
ktadd -k /home/jpmovie/mongos.keytab -norandkey mongos/[email protected]
ktadd -k /home/jpmovie/mongo.keytab -norandkey mongo/[email protected]

在MongoDB 的external数据库中增加Kerberos用户user1

免费天猫淘优惠券领取:http://q.jpmovie.cn

在Mongodb 的机器上运行命令 : mongod
mongo

use $external
 db.getSiblingDB("$external").createUser(
   {
     user: "user1/@EXAMPLE.COM",
     roles: [ { role: "readWrite", db: "kundatabase" } ]
   }
)

在MongoDB的机器上安装Kerberos client端

sudo apt-get install krb5-user libpam-krb5 libpam-ccreds auth-client-config libsasl2-modules-gssapi-mit
sudo dpkg-reconfigure krb5-config
- 输入对应的realm 和 KDC server的host名字

以kerberos认证的方式启动MongoDB服务

- 将KDC 服务器生成的mongodb.keytab 文件复制到MongoDB服务器中

- export KRB5_KTNAME=/home/hekun/KerberosData/kb5keytab/mongodb.keytab
测试从Mongodb 的服务器能不能通过kerberos连到KDC 的服务器:

kinit [email protected]
如果成功可以用 klist 来查看 TGT情况

启动MongoDB
 mongod --auth --setParameter authenticationMechanisms=GSSAPI

测试连接
- kinit [email protected]
- mongo --host mongohost.com --authenticationMechanism=GSSAPI --authenticationDatabase='$external' --username [email protected]
- use kundatabase
- show collections

JAVA通过Kerberos 连接MongoDB

实际上有三种方式通过Kerberos认证连接MongoDB

  • Username and password
  • Key Tab files
  • kinit (或者说是local cache).

具体JAVA实现代码:

  • 1,创建JAVA JAAS configuration

    import java.security.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;
    import com.sun.security.auth.module.*;
    
    public class KrbConfig 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", "true");
//                paramMap.put("useSubjectCredsOnly", "false");
//
//                //2.use keytab file
//                paramMap.put("doNotPrompt", "false");
//                paramMap.put("useKeyTab", "true");
//                paramMap.put("keyTab", "C:\\dataprovideagent\\krb5\\user.keytab");
//                paramMap.put("principal", "[email protected]");
//                
//                paramMap.put("useTicketCache", "true");
//                paramMap.put("ticketCache", "C:\\Users\\i322353\\krb5cc_I322353");
//                paramMap.put("useFirstPass", "true");
//                paramMap.put("tryFirstPass", "true");
//
//                paramMap.put("renewTGT", "true"); 
//                paramMap.put("refreshKrb5Config", "true");
//                String ticketCache = System.getenv("KRB5CCNAME");
//                System.out.println("%%%%%%%%%%%%%% "+ticketCache );
//                
//                if (ticketCache != null) { 
//                    paramMap.put("ticketCache", ticketCache); 
//                  } 
//
                
                Security.setProperty("javax.security.auth.login.name", "user");
                Security.setProperty("javax.security.auth.login.password", "123456");
                System.setProperty("javax.security.auth.login.name", "user");
                System.setProperty("javax.security.auth.login.password", "123456");
                
                paramMap.put("debug", "true");
                //1.enter the username and passsword 
               // paramMap.put("storeKey", "false");
                //paramMap.put("doNotPrompt", "true");
                //paramMap.put("useSubjectCredsOnly", "true");

                //2.use keytab file
                paramMap.put("useKeyTab", "true");
                paramMap.put("keyTab", "C:\\dataprovideagent\\krb5\\user.keytab");
                paramMap.put("principal", "[email protected]");
                
                paramMap.put("useTicketCache", "false");
                //paramMap.put("ticketCache", "C:\\Users\\i322353\\krb5cc_I322353");
                paramMap.put("useFirstPass", "false");
                paramMap.put("tryFirstPass", "false");

                paramMap.put("renewTGT", "false"); 
               // paramMap.put("refreshKrb5Config", "true");
                entry[0] = krb5LoginModule;

            }
            return entry;
        }

}
  • 2,创建main类,然后创建mongoclient端连接数据库

注意,这里是先登录kdc,然后再写一个action连接mongodb

package com.user.mongodb.main;

import java.io.File;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.Security;
import java.util.Arrays;


import javax.security.auth.Subject;

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

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.user.mongodb.util.Krb5Configuration;
import com.user.mongodb.util.KrbConfig;


public class mongodbKerberos
{

    static String user = "mongouser";
    static char[] password = "mongouser".toCharArray();
    static String database = "kundatabase";
    public static void main(String[] args)
    {
        
      MongoClient client =createKubrosConnection();
        //testKerb5();
    }
    
        
    public static MongoClient createKubrosConnection(){
        String loginModuleName = "KerberosLogin";
        Subject subject = new Subject();
        KrbConfig conf = new KrbConfig();
        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());
            Subject subject2 =   context.getSubject();
            
            MongoCredential credential = MongoCredential
                    .createGSSAPICredential("[email protected]");
//            PrivilegedExceptionAction action1  = ()->new MongoClient(new ServerAddress("mo-51e071c98.mo.sap.corp", 27017),
//                    Arrays.asList(credential));
            PrivilegedExceptionAction action1  = new PrivilegedExceptionAction() {

                @Override
                public MongoClient run() throws Exception
                {
                    // TODO Auto-generated method stub
                    MongoClient result = new MongoClient(new ServerAddress("mongohost.com.corp", 27017),
                            Arrays.asList(credential));
                    MongoDatabase ssfdfd = result.getDatabase("kundatabase");
                    MongoIterable aadaa = ssfdfd.listCollectionNames();
                    MongoCursor itdd = aadaa.iterator();
//                    while(itdd.hasNext()){
//                        String next = itdd.next();
//                        System.out.println(next+" ********************** ");
//                    }
                    return result;
                }
                
            };
            //精品电影网:http://www.jpmovie.cn
            //免费内部优惠券领取:http://q.jpmovie.cn
           //免费开源工具代码:http://blog.jpmovie.cn
            //PrivilegedExceptionAction action = ()->mongoClient.getDatabase("kundatabase");
            MongoClient result = Subject.doAs(subject2, action1);
            MongoDatabase ssfdfd = result.getDatabase("kundatabase");
            MongoIterable aadaa = ssfdfd.listCollectionNames();
            MongoCursor itdd = aadaa.iterator();
            while(itdd.hasNext()){
                String next = itdd.next();
                System.out.println(next+" 222********************** ");
            }
        } catch (LoginException | PrivilegedActionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
//          System.setProperty("java.security.krb5.realm", "EXAMPLE.COM");
//          System.setProperty("java.security.krb5.kdc", "mo-6851b47ac.mo.sap.corp");
//          
//          System.setProperty("javax.security.auth.login.name", "user");
//          System.setProperty("javax.security.auth.login.password", "123456");
//          Security.setProperty("javax.security.auth.login.name", "user");
//          Security.setProperty("javax.security.auth.login.password", "123456");
          
//        MongoCredential credential = MongoCredential
//                .createGSSAPICredential("[email protected]");
//        MongoClient  mongoClient = new MongoClient(new ServerAddress("mo-51e071c98.mo.sap.corp", 27017),
//                Arrays.asList(credential));
//        
//        MongoDatabase ssfdfd = mongoClient.getDatabase("kundatabase");
//        MongoIterable aadaa = ssfdfd.listCollectionNames();
//        MongoCursor itdd = aadaa.iterator();
//        while(itdd.hasNext()){
//            String next = itdd.next();
//           // System.out.println(next);
//        }
        return   null;
        
        
//        MongoClientConfiguration config = new MongoClientConfiguration("mongodb://locahost:27017/");
//        MongoCredential = 
//        config.addCredential(Credential.builder()
//                      .userName("[email protected]")
//                      .password("123456".toCharArray())
//                      .kerberos());
        
    }
    
    public static void testKerb5(){
        
        System.setProperty("java.security.krb5.realm", "EXAMPLE.COM");
        System.setProperty("java.security.krb5.kdc", "mongohost.com.corp");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
        
        System.setProperty(Krb5Configuration.KRB_DO_NOT_PROMPT, "true");// use true as default
        System.setProperty(Krb5Configuration.KRB_PRINC, "[email protected]");
        //http://www.jpmovie.cn
        // TBD Keytab type
        System.setProperty(Krb5Configuration.KRB_USE_KEY_TAB, "true");
        System.setProperty(Krb5Configuration.KRB_KEYTAB, "C:\\dataprovideagent\\krb5\\user.keytab");
        
        File file = new File("C:\\dataprovideagent\\krb5\\user.keytab");
        System.out.println(file.getAbsolutePath());
        
        Security.setProperty("login.configuration.provider", "com.user.mongodb.util.Krb5Configuration");
        
        MongoCredential credential = MongoCredential.createGSSAPICredential("[email protected]");
        
        MongoClient  mongoClient = new MongoClient(new ServerAddress("mo-51e071c98.mo.sap.corp", 27017),
                Arrays.asList(credential));
        
        MongoDatabase ssfdfd = mongoClient.getDatabase("kundatabase");
        MongoIterable aadaa = ssfdfd.listCollectionNames();
        MongoCursor itdd = aadaa.iterator();
        while(itdd.hasNext()){
            String next = itdd.next();
            System.out.println(next);
        }
    }
    
    private static void testMongoClient(MongoClient mongoClient)
    {
        try
        {
            MongoIterable databases = mongoClient.listDatabaseNames();
            if (null == databases || databases.first() == null)
            {
                System.out.println(
                        "Can not connect to MongoDB ,please check the remote source properties");
            }
        }
        catch (Exception e)
        {
            System.out.println(
                    "Can not connect to MongoDB : " + e.getMessage());
        }
    }

}

纳米虫分布式网页爬虫:http://nanoworm.jpmovie.cn

你可能感兴趣的:(MongoDB 配置Kerberos 认证,并用JAVA连接)