【问题标题】:Spring Boot MongoDB connection beanSpring Boot MongoDB 连接 bean
【发布时间】:2016-05-12 14:40:02
【问题描述】:

我有这样的情况。

我使用的是 Spring boot 1.3.2,我已经在我的电脑上安装了 MongoDB 我添加了依赖

org.springframework.boot:spring-boot-starter-data-mongodb

当我运行我的网络应用程序时,数据库连接会自动开始工作。

我没有配置任何东西。

现在我想像这样连接spring security:

@Override
protected void configure(AuthenticationManagerBuilder auth)
                                                   throws Exception {
  auth
    .jdbcAuthentication()
      .dataSource(dataSource);
}

我的问题是 Spring Boot DataSource 的默认 bean 名称是什么,我可以覆盖它吗?

【问题讨论】:

    标签: spring mongodb spring-security spring-boot spring-data


    【解决方案1】:

    如果您打算使用Mongodb 作为您的用户详细信息存储,即用户名密码等,那么您不能 使用jdbcAuthentication()。相反,您可以使用UserDetailsService 来达到同样的效果:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired private MongoTemplate template;
    
        @Override
        @Autowired
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                    .userDetailsService((String username) -> {
                        User user = template.findOne(Query.query(Criteria.where("username").is(username)), User.class, "users");
    
                        if (user == null) throw new UsernameNotFoundException("Invalid User");
    
                        return new UserDetails(...);
                    });
        }
    }
    

    在前面的示例中,我假设您有一个带有 username 字段的 users 集合。如果给定的 username 只存在一个用户,则应返回与该用户对应的 UserDetails 的实现。否则,你应该抛出一个UsernameNotFoundException

    您还有其他处理用户身份验证的选项,但jdbcAuthentication() 不在讨论范围内,因为您使用NoSQL 数据存储来存储用户详细信息,而JDBC 是处理所有与关系数据库。

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 2021-03-15
      • 2017-11-14
      • 2017-08-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 2015-07-14
      • 2021-06-06
      相关资源
      最近更新 更多