Security and Authentication

本文介绍 MongoDB 的安全配置及认证流程,包括用户管理、密码更改与删除操作,并详细阐述了副本集与分片环境下如何设置 key 文件进行内部通信验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mongo Security

You authenticatea username and password (加密方式) in the context ofa particular database. 

  • Once authenticated, a normal user has full read and write access to the database. 
  • You can also create read-only users that only have read access.

The admin database is special.  Several administrative commands can only run on the admin database.Also, authentication on admin gives a user read and write access to all databases on the server.//直接就有权限

Logging in using an admin account

Although admin user accounts can access any database, you must log into the admin database. For example, if someAdminUser has an admin account, this login will fail:

> use test
> db.auth("someAdminUser", password)

This one will succeed:

> use admin
> db.auth("someAdminUser", password)

  1. To enable security, run the database (mongod process) with the --auth option (or --keyFile for replica sets and sharding). Youmust either have added a user to the admin db before starting the server with authentication, 
  2. or add the first user from the localhost interface.//远程不可以


Configuring Authentication and Security

$ ./mongo
> use admin
> db.addUser("theadmin", "anadminpassword")

We now have a user created for database admin.Note that if we have not previously authenticated, we now must if we wish to perform further operations, as there is now an admin user.

> db.auth("theadmin", "anadminpassword")

Now, let's configure a "regular" user for another database.

> use projectx
> db.addUser("joe", "passwordForJoe")

Finally, let's add a readonly user. (only supported in 1.3.2+)

> use projectx
> db.addUser("guest", "passwordForGuest", true)

Viewing Users

User information is stored in each database's system.users collection. For example, on a database projectx,projectx.system.users will contain user information.

We can view existing users for the current database with the query:

> db.system.users.find()

Changing Passwords

The shell addUser command may also be used to update a password: if the user already exists, the password simply updates.

Deleting Users

To delete a user:

db.removeUser( username )

or

db.system.users.remove( { user: username } )

Replica Set and Sharding Authentication

The only difference is that the servers use a key file to authenticate internal communication. A key file is basically a plaintext file which is hashed and used as an internal password.(用于Server之间的交流,而不是用户连接服务器)

To set up replica sets and/or sharding with authentication:

  1. Create a key file that can be copied to each server in the set. A key file is composed of characters in the Base64 set, plus whitespace and newlines (see About the Key File for details).
  2. Modify this file's permissions to be only readable by the current user.
  3. Start each server in the cluster (including all replica set members, all config servers, and all mongos processes) with the --keyFile /path/to/file option.
  4. Each client connection to the database must be authenticated before it can be used, as with single-server authentication.

You do not need to use the --auth option, too (although there's no harm in doing so), --keyFile implies --auth--auth does not imply --keyFile.

About the Key File

A key file must contain at least 6 Base64 characters and be no larger than 1KB (whitespace included). Whitespace characters are stripped (mostly for cross-platform convenience), so the following keys are identical to the database:

$ echo -e "my secret key" > key1
$ echo -e "my secret key\n" > key2
$ echo -e "my    secret    key" > key3
$ echo -e "my\r\nsecret\r\nkey\r\n" > key4 -e     //enable interpretation of backslash escapes

If you run mongod with -v, the key will be printed in the log.

example

    Example

    If we had a two-member replica set with members a and b, we could start them up with authentication enabled by running:

    a$ echo "this is my super secret key" > mykey
    a$ chmod 600 mykey
    a$ mongod --keyFile mykey # other options...
    
    b$ echo "this is my super secret key" > mykey
    b$ chmod 600 mykey
    b$ mongod --keyFile mykey # other options...
    

    Then run rs.initiate() and so on.

    Using the Database with Replica Set Authentication On

    From the client's perspective, authentication works the same way with replica sets as it does with single servers.

    For example, suppose you create a new replica set and start the members with --keyFile. Connect to the master locally to add users:

    master$ mongo
    MongoDB shell version: x.y.z
    connecting to: test
    > db.addUser("foo", "bar")
    

    Clients should authenticate as usual when they make connections.

    any-member$ mongo -u foo -p
    MongoDB shell version: x.y.z
    Enter password: <bar>
    

    Key file permissions

    On *NIX, group and everyone must have 0 permissions (up to 700 is allowed). If the permissions are too open on the key file, MongoDB will exit with an error to that effect. ????

    Ports

    Default TCP port numbers for MongoDB processes are as follows:

    • Standalone mongod : 27017
    • mongos : 27017
    • shard server (mongod --shardsvr) : 27018  
    • config server (mongod --configsvr) : 27019
    • web stats page for mongod : add 1000 to port number (28017, by default).  Most stats pages in the HTTP UI are unavailable unless the --rest option is specified.  To disable the "home" stats page use --nohttpinterface.  (This port should be secured, if used, however, the information on the stats home page is read only regardless.)???

    IP Address Binding

    By default, a mongod server will listen on all available IP addresses on a machine. You can restrict this to a single IP address with the'bind_ip' configuration option for mongod.

    Typically, this would be set to 127.0.0.1, the loopback interface, to require that mongod only listen to requests from the same machine (localhost).

    To enable listening on all interfaces, remove the bind_ip option from your server configuration file.

    在 Spring Security 中,`Authentication` 对象是用来表示用户已经通过身份验证的信息。如果你想在认证中包含 IP 地址,虽然这不是标准做法,但是你可以通过自定义实现来做到这一点。这里是一个简单的例子: 首先,创建一个自定义的 `UserDetails` 接口或者实现 `AbstractUserDetails` 并添加一个新的属性来保存 IP 地址: ```java public class CustomUserDetails extends AbstractUserDetails { private String username; private String ipAddress; // getters and setters } ``` 然后,在你的认证处理器(如 `UserServiceAuthenticationProvider` 或者 `UsernamePasswordAuthenticationFilter` 的实现)里,你可以这样做: ```java @Override protected UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { CustomUserDetails userDetails = ...; // 这里应该是从数据库或者其他数据源获取用户的详细信息,包括 IP 地址 userDetails.setIpAddress("your_ip_address"); return userDetails; } ``` 最后,确保你在构建 `Authentication` 对象时包含了这个自定义信息: ```java Authentication authentication = new UsernamePasswordAuthenticationToken( userDetails, userDetails.getPassword(), // 用户密码 userDetails.getAuthorities() ); // 添加 IP 地址作为额外的属性,这通常是安全考虑,因为不应该直接放入 Authentication 对象 Map<String, Object> details = new HashMap<>(); details.put("ipAddress", userDetails.getIpAddress()); authentication.setDetails(details); ``` 注意,这样的设计并不是最佳实践,因为 `Authentication` 对象通常只包含用户名、密码等核心信息,而 IP 地址可以被视为敏感数据,不应随意存储。但在某些特定场景下,比如审计日志或安全策略中可能需要这样做。
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值