Soap UI Groovy脚本访问授权的MongoDB
备注:根据自己的遇见的问题写的随笔,不一定通用,仅供参考
问题:
通过NOSQLManager连接授权的MongoDB,连接成功。
通过Groovy脚本连接授权的MongoDB,授权方式是:SCRAM-SHA-1+用户名+密码,因为授权失败连接不成功。
开始用的是:MongoCredential.createScramSha1Credential
MongoCredential credential =MongoCredential.createScramSha1Credential("mongodb","NGSystem",Psw as char[])
Error信息:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=XX.XX.XX.XX:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='mongodb', source='NGSystem', password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server XX.XX.XX.XX:27017. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}] error at line: 43
解决方案:
把以下Jar包Copy到SoapUIPro Bin/ext和lib目录下:
mongodb-driver-3.4.0-rc1.jar
mongo-java-driver-3.4.0-rc1.jar
gmongo-1.5.jar
2.因为从v3.0 +版本才开始使用SCRAM-SHA-1授权方式,所以要求mongo-java-driver版本在3.0以上,同时一定要删除旧版本的mongo-java-driver,否则默认使用旧版本的构造方法。
3.把MongoCredential.createScramSha1Credential换成MongoCredential.createCredential
Groovy代码:
import java.util.*;
import com.gmongo.GMongoClient
import com.mongodb.MongoCredential
import com.mongodb.ServerAddress
import com.mongodb.MongoClientOptions
importcom.mongodb.client.MongoDatabase;
credentials =MongoCredential.createCredential('mongodb', 'admin', 'mongodb' as char[])
//MongoClientOptions options = MongoClientOptions.builder().serverSelectionTimeout(1000)
GMongoClient client = new GMongoClient(newServerAddress("XX:XX:XX:XX",27017), [credentials])
def DB= client.getDB("NGSystem").Role.find()
DB.each
{
log.info(it)
}