简体   繁体   English

使用Java 3.0驱动程序检查MongoDB身份验证

[英]Check MongoDB authentication with Java 3.0 driver

I am currently trying to connect to a MongoDB replica set using the (relatively) new 3.0 Java driver. 我目前正在尝试使用(相对)新的3.0 Java驱动程序连接到MongoDB副本集。 However I can't seem to catch the MongoSecurityExceptions that occur when the user provides bad credentials. 但是,我似乎无法捕获用户提供错误凭据时发生的MongoSecurityExceptions。 This is my current code. 这是我目前的代码。

try {
    MongoClientURI mongoClientURI = new MongoClientURI("mongodb://<user>:<password>@member1.com:27017/?authSource=db"
    this.mongoClient = new MongoClient(mongoClientURI);
}
catch(Exception e) {
    // TODO: some proper exception handling
    System.err.println(e.toLocalizedMessage());
}

This code works fine when run with correct credentials, but an exception is thrown outside of the try-catch when bad credentials are provided. 使用正确的凭据运行时,此代码可以正常工作,但在提供错误的凭据时,会在try-catch之外抛出异常。

com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='<user>', source='<source>', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
at java.lang.Thread.run(Thread.java:745)

Any idea where to handle authentication exceptions? 知道在哪里处理身份验证异常?

The MongoClient constructors do not throw any connectivity-related exceptions. MongoClient构造函数不会抛出任何与连接相关的异常。 Rather, they return immediately after starting one or more background threads that attempt to establish a connection and authenticate based on the provided credentials. 相反,它们在启动一个或多个后台线程后立即返回,这些后台线程尝试建立连接并根据提供的凭据进行身份验证。

It's only when an application uses the MongoClient to perform some operation on the MongoDB server that an exception will be thrown. 只有当应用程序使用MongoClient在MongoDB服务器上执行某些操作时才会抛出异常。 However, that exception is a generic timeout exception indicating that the driver failed to find a suitable server for the operation before the server selection timeout expires. 但是,该异常是一个通用超时异常,表示驱动程序在服务器选择超时到期之前未能为该操作找到合适的服务器。 For example: 例如:

    MongoClient client = new MongoClient(asList(new ServerAddress("localhost"), new ServerAddress("localhost:27018")),
                                         singletonList(MongoCredential.createCredential("username",
                                                                                        "admin",
                                                                                        "bad".toCharArray())),
                                         MongoClientOptions.builder().serverSelectionTimeout(1000).build());


    try {
        client.getDB("admin").command("ping");
    } catch (MongoTimeoutException e) {
        // do something
    }

will throw a MongoTimeoutException after 1 second. 将在1秒后抛出MongoTimeoutException。 While no MongoSecurityException is thrown, the message of the MongoTimeoutException will contain relevant details. 虽然没有抛出MongoSecurityException,但MongoTimeoutException的消息将包含相关的详细信息。 For example, when connecting to a three member replica set when one of the servers is down, and authentication failed on the remaining two, the message field of the MongoTimeoutException will be something like: 例如,当其中一个服务器关闭时连接到三个成员副本集,并且其余两个服务器上的身份验证失败时,MongoTimeoutException的消息字段将类似于:

Timed out after 1000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. 在等待与ReadPreferenceServerSelector {readPreference = primary}匹配的服务器时,在1000毫秒后超时。 Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='username', source='admin', password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' 集群状态的客户端视图是{type = UNKNOWN,servers = [{address = localhost:27017,type = UNKNOWN,state = CONNECTING,exception = {com.mongodb.MongoSocketOpenException:Exception opening socket},由{java.net引起。 ConnectException:Connection refused}},{address = localhost:27018,type = UNKNOWN,state = CONNECTING,exception = {com.mongodb.MongoSecurityException:异常验证MongoCredential {mechanism = null,userName ='username',source ='admin' ,password =,mechanismProperties = {}}},由{com.mongodb.MongoCommandException引起:命令失败,错误18:'身份验证失败。' on server localhost:27018. 在服务器localhost:27018。 The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." 完整的响应是{“ok”:0.0,“code”:18,“errmsg”:“身份验证失败。” }}}] }}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM