`

Java MongoDB : Authentication 例子(译)

阅读更多

 

原文出自:http://www.mkyong.com/mongodb/java-authentication-access-to-mongodb/

返回目录:http://ysj5125094.iteye.com/blog/2192754 

 

Java MongoDB : Authentication example

By default, MongoDB is run in trust environment (authentication with a username and password is NOT required). In this tutorial, we will show you how to start MongoDB in secure mode / enable authentication, and connect with the Java MongoDB driver.

译:默认情况下,MongoDB 运行在一个信任的环境里(是不需要用户名和密码认证的)。在本教程中,我们将向你展示如何在安全模式下启动MongoDB / 启用身份验证,并通过Java程序连接MongoDB。

 

1. Start MongoDB in Secure Mode

Start MongoDB with --auth option, now, MongoDB need username and password to perform any database / collection operations.

译:启动MongoDB -- auth 选项,现在,MongoDB需要用户名和密码才能执行任何database/collection 操作。

mongod --auth

 

Later, we need to connect to the database “testdb”, so add a user for testing later.

译:接下来,我们需要连接数据库"testdb",所以添加一个测试用户。

> use admin
> db.addUser("admin","password")
> use testdb
> db.addUser("mkyong","password")

 

To enable MongoDB authentication, you must first add a user to the special “admin” database, please refer to this MongoDB authentication example for detail guide. 

译:使MongoDB的认证,你必须首先添加一个特殊的用户“admin”,请参阅此MongoDB实例验证详细指南。

 

 

2. Java + MongoDB Authentication example

If MongoDB is started in secure mode, below “insert” operation is no longer valid, and prompts “need to login” error message.

译:如果MongoDB已经运行在安全模块中,那么"insert"操作不再有效,并提示"需要登录"错误消息。

	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("testdb");
 
	DBCollection table = db.getCollection("user");
 
	BasicDBObject document = new BasicDBObject();
	document.put("name", "mkyong");
	table.insert(document);

 

com.mongodb.CommandResult$CommandFailure: command failed [getlasterror]: 
	{ "serverUsed" : "localhost/127.0.0.1:27017" , "errmsg" : "need to login" , "ok" : 0.0}
 
	at com.mongodb.CommandResult.getException(CommandResult.java:88)
	at com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
	at com.mongodb.DBTCPConnector._checkWriteError(DBTCPConnector.java:142)
	at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:183)
	at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
	at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
	at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
	at com.mongodb.DBCollection.insert(DBCollection.java:75)
	at com.mongodb.DBCollection.insert(DBCollection.java:59)
	at com.mongodb.DBCollection.insert(DBCollection.java:104)
	at com.mkyong.core.App.main(App.java:40)

 

Now, using db.authenticate() to perform the authentication, a return value of true = success, false = fail.

译:现在,使用db.authenticate()进认证,会得到一个返回值 true = 成功, false = 失败。

 

package com.mkyong.core;
 
import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * Java + MongoDB in Secure Mode
 * 
 */
public class JavaMongoDBAuthExample {
   public static void main(String[] args) {
 
    try {
 
	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("testdb");
 
	boolean auth = db.authenticate("testdb", "password".toCharArray());
	if (auth) {
 
		DBCollection table = db.getCollection("user");
 
		BasicDBObject document = new BasicDBObject();
		document.put("name", "mkyong");
		table.insert(document);
 
		System.out.println("Login is successful!");
	} else {
		System.out.println("Login is failed!");
	}
	System.out.println("Done");
 
    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }
  }
}

 

References

  1. Java MongoDB authentication example
  2. JIRA – DB.authenticate() should use a char[] for the password
  3. MongoDB Java Authentication example
  4. MongoDB Security Practices and Management

 

 

 

0
0
分享到:
评论

相关推荐

    MongoDB: The Definitive Guide

    MongoDB: The Definitive Guide MongoDB is a powerful, flexible, and scalable general­purpose database. It combines the ability to scale out with features such as secondary indexes, range queries, ...

    MongoDB之Java使用例子

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); ``` 然后,选择或创建数据库: ```java MongoDatabase database = mongoClient.getDatabase("myDatabase"); ``` 接着是集合操作。...

    深入学习MongoDB:Scaling MongoDB && 50 Tips and Tricks for MongoDB Developers

    深入学习MongoDB:Scaling MongoDB && 50 Tips and Tricks for MongoDB Developers深入学习MongoDB中文版Scaling MongoDB英文版50 Tips and Tricks for MongoDB Developers英文版高清完整目录3本打包合集

    Windows上安装MongoDB:完整步骤详解.pdf

    1. 连接MongoDB:输入`mongo.exe`命令,连接到本地MongoDB服务。 2. 创建数据库:使用`use <database_name>`命令,如`use testdb`,创建一个名为"testdb"的数据库。 3. 插入数据:在选定的数据库中,使用`db....

    Spring Data MongoDB : Update document

    **Spring Data MongoDB: 更新文档** 在现代Web应用开发中,数据存储是至关重要的部分,而MongoDB作为NoSQL数据库中的代表,因其灵活性和高性能而受到广泛欢迎。Spring Data MongoDB是Spring框架的一个模块,它简化...

    Java连接mongoDB需要的jar包(3.9.1)

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("testDB"); // ...其他数据库操作 } } ``` 以上代码展示了如何创建一个到...

    通过java向mongodb中插入数据

    MongoClient mongoClient = MongoClients.create("mongodb://192.168.46.195:10001"); MongoDatabase database = mongoClient.getDatabase("testDB"); MongoCollection<Document> collection = database....

    Mongodb数据库JAVA操作例子

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("yourDatabaseName"); MongoCollection<Document> collection = database....

    Java + MongoDB 实现 hello world 例子(译)

    public static MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); public static MongoDatabase database = mongoClient.getDatabase("hello_world_db"); public static ...

    java+MongoDB实现存图片、下载图片的方法示例

    "java+MongoDB实现存图片、下载图片的方法示例" 本文主要介绍了使用java和MongoDB实现存图片和下载图片的方法,并结合实例形式详细分析了java结合MongoDB实现图片的存储和下载相关操作技巧。 Java和MongoDB简介 ...

    MongoDBjava各版本驱动下载

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); ``` 4. 使用基本操作: - 连接数据库:`MongoDatabase db = mongoClient.getDatabase("databaseName");` - 操作集合:`...

    java 操作mongodb 增删改查

    MongoClient mongoClient = MongoClients.create("mongodb://root:root@localhost:27017"); // 获取名为"mydb"的数据库 MongoDatabase database = mongoClient.getDatabase("mydb"); ``` 现在,你可以对数据库进行...

    sql-to-mongodb:将SQL表转换为MongoDB集合的Java工具

    将SQL表转换为MongoDB集合的Java工具 轻松将 MSSQL 表转换为 MongoDB。 从下载 SQL Server JDBC 驱动程序 将 SQLJDBC4.jar 文件放在同一文件夹中。 一次指定 TABLE NAME 和 NUMBER OF ROWS 进行导入。 java -...

    spring结合mongodb例子(maven java project)

    spring-data-mongodb:1.1.0 java:1.8 log4j:1.2.16 junit:4.12 commons-logging:1.1.1 maven:3 注意:spring的不同版本与mongodb结合可能会有问题,自测:spring4.2.1结合mongodb会报错:**springframework.core....

    java实现mongodb数据库的操作

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); ``` 五、数据库与集合操作 1. 获取数据库:使用`MongoDatabase`对象表示数据库,例如`mydb`。 ```java MongoDatabase database = ...

    MySQL vs MongoDB

    - MongoDB:以键值对、文档、集合的形式存储数据,灵活的数据结构,适合半结构化和非结构化数据。 2. 查询语言: - MySQL:使用SQL(结构化查询语言)进行查询,支持JOIN操作,适合处理结构化关系数据。 - ...

    jdbc java mongodb mysql 相互同步

    本文将深入探讨如何使用Java的JDBC(Java Database Connectivity)接口与MongoDB、MySQL数据库进行数据交互,并实现相互之间的数据同步。 首先,我们需要理解JDBC,它是Java语言访问数据库的标准API,能够连接并...

    java连接mongodb的jar包

    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("myDatabase"); System.out.println("Connected to MongoDB!"); mongoClient...

    掌握MongoDB:NoSQL数据库基础与高级特性教程.rar

    什么是 MongoDB MongoDB 简介 MongoDB 特点 安装与配置 安装 MongoDB 启动与配置 MongoDB 基本操作 数据库和集合 文档操作 查询操作 基本查询 高级查询 索引与性能优化 创建索引 索引类型 索引优化 聚合操作 聚合...

    java连接mongodb3.4.2所需jar

    implementation 'org.mongodb:mongodb-driver-core:3.4.2' implementation 'org.mongodb:bson:3.4.2' } ``` 一旦添加了依赖,你就可以开始编写Java代码来连接MongoDB数据库。以下是一个基本的示例: ```java ...

Global site tag (gtag.js) - Google Analytics