Security and Authentication

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

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 是 Spring 生态中的安全框架,提供了完整的认证、授权和安全防护机制,其中 Authenticationtoken 在安全体系里发挥着重要作用。 ### Authentication Authentication 在 Spring Security 中代表用户的认证信息,是认证过程的核心对象。当用户尝试访问受保护资源时,Spring Security 会对用户进行认证,认证成功后会创建一个包含用户信息(如用户名、密码、权限等)的 Authentication 对象。这个对象会被存储在 SecurityContext 中,后续的授权操作会依据该对象来判断用户是否有权限访问资源。 ### Token Token 是一种轻量级的身份验证和授权机制,在 Spring Security 中使用 token 可实现无状态的认证。其整体流程为:用户通过认证后,系统会生成一个 token 并返回给前端;前端在后续请求的 header 中附带该 token;资源服务器接收到请求后,验证 token 的有效性并判定其权限,然后返回请求结果。在验证 token 有效性时,可根据实际情况定制验证方式,比如只验证 token 有效期和密钥,这种方式无需向数据库/缓存查询用户名和密码;也可以验证 token 中的用户是否存在,此方式则需要向数据库/缓存查询用户名 [^2]。 ### 使用示例 以下是一个简单的 Spring Security 中使用 token 认证的示例代码: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); } } ``` ```java import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @Component public class JwtAuthenticationFilter extends OncePerRequestFilter { private final UserDetailsService userDetailsService; private final JwtTokenUtil jwtTokenUtil; public JwtAuthenticationFilter(UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil) { this.userDetailsService = userDetailsService; this.jwtTokenUtil = jwtTokenUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = getTokenFromRequest(request); if (token != null && jwtTokenUtil.validateToken(token)) { String username = jwtTokenUtil.getUsernameFromToken(token); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(request, response); } private String getTokenFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } } ```
    评论
    成就一亿技术人!
    拼手气红包6.0元
    还能输入1000个字符
     
    红包 添加红包
    表情包 插入表情
     条评论被折叠 查看
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值