先将mongoDB现有用户全部删除:
[root@centos7 bin]# use admin;
[root@centos7 bin]# show tables;
[root@centos7 bin]# db.system.users.remove({});
先为mongoDB数据库创建一个超级用户:
[root@centos7 bin]# use admin;
先为mongoDB数据库创建一个超级用户:
[root@centos7 bin]# db.createUser({"user":"administrator","pwd":"welcome","roles":["root"]});
创建成功返回值:
Successfully added user: { "user" : "administrator", "roles" : [ "root" ] }
然后结束mongoDB服务,以加密的方式重新启动:
[root@centos7 bin]# ./mongod -auth
此时你发现你不用密码依然可以执行 ./mongo 命令连接.,但是当你操作数据库的时候会遇到阻碍:
2017-07-28T09:49:43.033+0800 E QUERY [thread1] Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listCollections: 1.0, filter: {} }",
"code" : 13,
"codeName" : "Unauthorized"
} :
两种方法可以在命令行里操作加密的数据库:
第一种,连接的时候附带上用户名和密码:
[root@centos7 bin]# mongo -u administrator -p welcome --authenticationDatabase "admin"
第二种,连接进去之后再验证用户名密码:
[root@centos7 bin]# use admin;
[root@centos7 bin]# db.auth("administrator","welcome");
下面是在java代码中连接:
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("10.168.10.41",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("administrator", "admin", "welcome".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
Document buildInfo = mongoDatabase.runCommand(new Document("serverStatus", 1));
System.out.println(buildInfo.get("host"));