[英]How to configure 2 databases with common user (which has access to both of them) in one app?
[英]How to get list of databases in mongodb for which user is having access?
是否可以在 Mongodb 中獲取特定用戶有權訪問的數據庫列表?
在 MongoDB shell 中,以下命令將列出數據庫:
db.adminCommand('listDatabases')
或者
db.getMongo().getDBNames()
對於當前的 Java API,使用MongoClient的listDatabaseNames()
方法,該方法返回一個包含所有數據庫名稱的可迭代對象。 例如(未經測試):
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class JavaMongoDBConnection {
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoIterable<String> allDatabases = mongoClient.listDatabaseNames();
for (String dbName : allDatabases) {
DB db = mongoClient.getDB(dbName);
char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
boolean authenticated = db.authenticate("user", password);
if (authenticated) {
System.out.println("Successfully logged in to MongoDB!");
System.out.println("Database: " + dbName);
Set<String> collections = db.getCollectionNames();
for (String colName : collections) {
System.out.println("\t + Collection: " + colName);
}
} else {
System.out.println("Invalid username/password");
}
}
mongoClient.close();
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
}
您可以通過在system.users集合中查找該用戶來檢查特定用戶的訪問權限。 他們可以在角色鍵下的db鍵上添加投影。
這是用戶集合中 doc 的結構。
{
_id: <system defined id>,
user: "<name>",
db: "<database>",
credentials: { <authentication credentials> },
roles: [
{ role: "<role name>", db: "<database>" },
...
],
customData: <custom information>
}
從 4.0.5 MongoDB 開始, listDatabases 中有一個選項可以只過濾授權的數據庫:
authorizedDatabases [boolean] [Optional]:當啟用訪問控制時,根據用戶權限確定返回哪些數據庫的標志。
它可能是這樣的:
return mongoClient.getDatabase("admin").runCommand(
new BasicDBObject("listDatabases",
new BasicDBObject("authorizedDatabases", 1)
)
);
閱讀完整文檔,因為版本之間存在一些細微差別:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.