MongoDB增加身份验证

1. 数据库添加用户和密码

mongo
>use admin
>db.createUser({user:"nucRoot",pwd:"f71F!6",roles:[{role: "root", db: "admin"}]})
注意:较高版本的DB Server(6+)不支持mongo,需要使用mongosh,可以使用compass附带的mongosh

 

2. 修改启动文件,通过auth方式启动,完整如下(INI格式)

dbpath=/usr/local/mongodb/data/db
logpath=/usr/local/mongodb/data/logs/mongodb.log
logappend=true
journal=true
bind_ip=0.0.0.0
port=27017
fork=true
auth=true

 

3. 修改服务配置文件application.properties,相关配置如下

#spring.data.mongodb.uri=mongodb://localhost:27017/neptune

spring.data.mongodb.username=nucRoot
spring.data.mongodb.password=ENC(AwrUSlL/w4Muk=)
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=uranus
spring.data.mongodb.authentication-database=admin

 

相关设计:

项目pom.xml添加

<!-- jasypt -->
<dependency>
   <groupId>com.github.ulisesbocchio</groupId>
   <artifactId>jasypt-spring-boot-starter</artifactId>
   <version>3.0.3</version>
</dependency>

设置jasypt

public static void main(String[] args) {
              
     //ApplicationTests will NOT know!!!
     System.setProperty("jasypt.encryptor.password", "xxxx");
     System.setProperty("jasypt.encryptor.algorithm", "PBEWithMD5AndTripleDES");
     //
     SpringApplication.run(UranusApplication.class, args);
}

 

posted @ 2024-09-18 15:24  jason47  阅读(31)  评论(0编辑  收藏  举报