mongo-java-driver -3.2.2学习笔记-05-身份认证

百里丁雨
2023-12-01

An authentication credential is represented as an instance of the MongoCredential class, which includes static factory methods for each of the supported authentication mechanisms. A list of these instances must be passed to the driver via one of several MongoClient constructors that take a parameter of type List. Alternatively, a single MongoCredential can be created implicity via a MongoClientURI and passed to a MongoClient constructor that takes a MongoClientURI parameter.

方法一

import com.mongodb.MongoCredential;

// ...

String user;        // the user name
String database;    // the name of the database in which the user is defined
char[] password;    // the password as a character array
// ...
MongoCredential credential = MongoCredential.createCredential(user,
                                                              database,
                                                              password);

方法二

MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1");

不同的身份认证策略
策略1:

MongoCredential credential = MongoCredential.createScramSha1Credential(user,
                                                                       database,
                                                                       password);
MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&authMechanism=SCRAM-SHA-1");

策略2:

MongoCredential credential = MongoCredential.createMongoCRCredential(user,
                                                                     database,
                                                                     password);
MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&authMechanism=MONGODB-CR");

策略3:

String user;     // The x.509 certificate derived user name, e.g. "CN=user,OU=OrgUnit,O=myOrg,..."
MongoCredential credential = MongoCredential.createMongoX509Credential(user);
MongoClientURI uri = new MongoClientURI("mongodb://subjectName@host1/?authMechanism=MONGODB-X509");

策略4:

String user;   // The Kerberos user name, including the realm, e.g. "user1@MYREALM.ME"
// ...
MongoCredential credential = MongoCredential.createGSSAPICredential(user);
MongoClientURI uri = new MongoClientURI("mongodb://username%40REALM.com@host1/?authMechanism=GSSAPI");

策略5:

String user;          // The LDAP user name
char[] password;      // The LDAP password
// ...
MongoCredential credential = MongoCredential.createPlainCredential(user, "$external", password);
MongoClientURI uri = new MongoClientURI("mongodb://user1@host1/?authSource=$external&authMechanism=PLAIN");
 类似资料: