启用auth时,使用mongo java驱动程序复制db操作

时间:2014-07-11 06:07:50

标签: java mongodb

我需要使用mongo java驱动程序执行copydb操作。这是我的代码

String nonce = mongo.getDB("admin").command(new BasicDBObject("copydbgetnonce","1")).get("nonce").toString();
String username = "admin";
String password = "password";
String key = md5(nonce + username + md5(username + ":mongo:" + password));

DBObject copyOp = new BasicDBObject("copydb", "1").
  append("fromdb" , "db1").
  append("todb" , "db2").
  append("username" , username).
  append("nonce" , nonce).
  append("key" , key);

mongo.getDB("admin").command(copyOp);

在服务器上禁用身份验证时,它正在工作。通过身份验证,它会因未经授权的结果而失败。

{ "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "unauthorized"}

我可以确保密码和用户名是正确的。请指出正确的方向。

PS我的mongod实例是tokumx 1.5

感谢。

1 个答案:

答案 0 :(得分:1)

这对你有用吗?

final DBObject cmd = new BasicDBObject( );
cmd.put( "copydb", "1" );
cmd.put( "slaveOk", true );
cmd.put( "fromdb", "db1" );
cmd.put( "todb", "db2" );
cmd.put( "fromhost", "fromHost" );

BasicDBObject nonceCmd = new BasicDBObject( );
nonceCmd.put( "copydbgetnonce", 1 );
nonceCmd.put( "fromhost", "fromHost" );
final CommandResult nonceResult = mongo.getDB( "admin" ).command( nonceCmd );
final String nonce = nonceResult.getString( "nonce" );
final byte[ ] innerHex =( getUserName( ) + ":mongo:" + String.valueOf( getPassword( ) ) ).getBytes( );
final byte[ ] outerHex = ( nonce + getUserName( ) + Util.hexMD5( innerHex ) ).getBytes( );

cmd.put( "username", getUserName( ) );
cmd.put( "nonce", nonce );
cmd.put( "key", Util.hexMD5( outerHex ) );

final CommandResult res = mongo.getDB( "admin" ).command( cmd );
if ( !res.ok( ) )
{
    throw res.getException( ) ;
}