如何使用mongodb

时间:2019-03-27 05:25:40

标签: java mongodb spring-boot

我正在做我的B.Tech项目,一切进展顺利,但现在我被困在为两种不同类型的用户(即客户和服务提供商)配置身份验证。我正在使用MongoDB。

我为每个用户有两个不同的数据库。我正在尝试创建多个登录页面,以从各自的数据库中对用户进行身份验证。我正在使用order(1)和order(2)进行配置,但是只有order(1)在工作。

这是我的配置代码。

       @Configuration
       @EnableWebSecurity
       public class MultiLoginConfig {

@Configuration
@Order(1)
public static class DearHelpUserSecConfig extends WebSecurityConfigurerAdapter{

      @Override
        @Bean
        protected UserDetailsService userDetailsService() {
            return new CustomUserDetailsService();
        }

      @Bean
        public static NoOpPasswordEncoder passwordEncoder() {
         return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .antMatchers( "/home").permitAll()
                .antMatchers("/hellouser").access("hasRole('USER')")

                .and()
            .formLogin()

                .loginPage("/login1")
                .permitAll()
                .and()
            .logout()
              .permitAll()
            .logoutUrl("/logout"). 
            logoutSuccessUrl("/home")
                .and()
                    .userDetailsService(userDetailsService());
        }

}

@Configuration
@Order(2)
public static class DearHelpSPSecConfig extends WebSecurityConfigurerAdapter{

     @Override
        @Bean
        protected UserDetailsService userDetailsService() {
            return new SPUserDetailsService();
        }

        @Bean
        public static NoOpPasswordEncoder passwordEncoder() {
         return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .antMatchers( "/home").permitAll()
                .antMatchers("/hellosp").access("hasRole('SP')")

               .and()
            .formLogin()

                .loginPage("/login2")
                .permitAll()
                .and()
            .logout()
                .permitAll()
            .logoutUrl("/logout"). 
            logoutSuccessUrl("/home")
                .and()
                    .userDetailsService(userDetailsService());
        }


}   

  }

我正在为每个用户实现Custom UserDetailsS​​ervice。

Customers UserDetailsS​​ervices的自定义实现是..

   public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private MongoTemplate mongoTemplate;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Query query = new Query();
    query.addCriteria(Criteria.where("email").is(email));
    DearHelpUsers user =
            mongoTemplate.findOne(query, DearHelpUsers.class);
    if (user == null) {
        throw new UsernameNotFoundException(String.format("email %s not found", email));
    }



    return new User(user.getEmail(), user.getPassword(),
         AuthorityUtils.createAuthorityList(user.getRole()));

   }
 }                  

服务提供商UserDetailsS​​ervices的自定义实现是..

   public class SPUserDetailsService implements UserDetailsService {

@Autowired
private MongoTemplate mongoTemplate;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    Query query = new Query();
    query.addCriteria(Criteria.where("email").is(email));
    ServiceProviders user =
            mongoTemplate.findOne(query, ServiceProviders.class);
    System.out.println(user);
    if (user == null) {
        throw new UsernameNotFoundException(String.format("email %s not found", email));
    }



    return new User(user.getEmail(), user.getPassword(),
         AuthorityUtils.createAuthorityList(user.getRole()));

   }
}

当我尝试访问“客户”页面(即“ / hellouser”)时,弹出登录页面,并且身份验证工作正常。 但是,当我尝试访问服务提供者页面(即“ / hellosp”)时,无需登录用户即可访问该页面。服务提供商的授权无效。 我尝试更改顺序,发现只有order(1)代码的授权有效,而order(2)无效。 我在哪里做错了? 任何帮助将不胜感激。 谢谢

1 个答案:

答案 0 :(得分:1)

@Configuration
@EnableMongoRepositories(basePackages = {"com.sbr.platform.services.repository.primary"},
        mongoTemplateRef = "primaryMongoTemplate")
@EntityScan(basePackages = "com.sbr.platform.services.model")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class PrimaryMongodbConfig {

}

创建辅助数据库配置

@Configuration
@EnableMongoRepositories(basePackages = {"com.sbr.platform.services.repository.secondary"}, mongoTemplateRef = "secondaryMongoTemplate")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class SecondaryMongodbConfig {

}
@Data
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(MongoConfigProperties.class)
@Slf4j
public class MultipleMongoConfig {

    private final MongoConfigProperties mongoConfigProperties;

    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(mongoFactory(this.mongoConfigProperties.getPrimary()), this.mongoConfigProperties.getPrimary().getDatabase());
    }

    @Primary
    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(mongoFactory(this.mongoConfigProperties.getSecondary()), this.mongoConfigProperties.getSecondary().getDatabase());
    }

    private MongoClient mongoFactory(final MongoProperties mongo) {
        StringBuffer sb = new StringBuffer();
        sb.append("mongodb://");
        sb.append(mongo.getUsername());
        sb.append(":");
        sb.append(mongo.getPassword());
        sb.append("@");
        sb.append(mongo.getHost());
        sb.append(":");
        sb.append(mongo.getPort());
        sb.append("/");
        sb.append(mongo.getDatabase());
        sb.append("?authSource=");
        sb.append(mongo.getAuthenticationDatabase());
        log.info("Connection String : {} ",sb.toString());
        MongoCredential credential = MongoCredential.createCredential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());
        log.info("mongoFactory : {} : credential: {} ", mongo, credential);
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString(sb.toString()))
                .build();
        return MongoClients.create(mongoClientSettings);
    }

}

application.yml

sbr:
  service:
    mongodb: # MongoDB configuration
      config:
        primary:
          host: localhost
          port: 27017
          database: primary-profiles-collections
          authentication-database: admin
          username: root
          password: example
          repositories:
            enable: true
        secondary:
          host: localhost
          port: 27017
          database: secondary-profiles-collections
          authentication-database: admin
          username: root
          password: example
          repositories:
            enable: true

使用不同的软件包创建2个存储库

@Repository
public interface ProfilePrimaryRepository extends MongoRepository<Profile, String> {
}

@Repository
public interface ProfileSecondaryRepository extends MongoRepository<Profile, String> {
}

在下面的代码中添加springboot主类

@Configuration
@Slf4j
public class ProfileApplicationConfig implements CommandLineRunner {

    @Autowired
    private ProfilePrimaryRepository profilePrimaryRepository;
    @Autowired
    private ProfileSecondaryRepository profileSecondaryRepository;

    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {
        Profile profile = new Profile();
        profile.setProfileType(ProfileType.USER);
        User userProfile = new User();
        userProfile.setPassword("testPWD");
        userProfile.setUserName("test user");
        profile.setBaseProfile(userProfile);
        profile = profilePrimaryRepository.save(profile);
        log.info("Create Profile: {} ", profilePrimaryRepository.findAll());
    }
}

结果

ProfileApplicationConfig  : Create Profile: [Profile(profileType=USER, baseProfile=User(userName=test user, password=testPWD))]