[英]How to configure multiple login pages using multiple databases for authentication in springboot using mongodb
我正在做我的 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());
}
}
}
我正在为每个用户实现自定义 UserDetailsService。
客户 UserDetailsServices 的自定义实现是..
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()));
}
}
服务提供者 UserDetailsServices 的自定义实现是..
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) 无效。 我哪里做错了? 任何帮助将不胜感激。 谢谢
@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);
}
}
应用程序.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))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.