Java Code Examples for com.mongodb.MongoCredential#createScramSha1Credential()

The following examples show how to use com.mongodb.MongoCredential#createScramSha1Credential() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
private MongoCredential createCredentials(Map<String, Object> map) {
  final String authMechanismName = (String) map.get("authMechanism");
  final AuthenticationMechanism authenticationMechanism =
      AuthenticationMechanism.fromMechanismName(authMechanismName);
  final String username = (String) map.get("userName");
  final String authDatabase = (String) map.get("dbName");
  final String password = (String) map.get("password");

  switch (authenticationMechanism) {
  case PLAIN:
    return MongoCredential.createPlainCredential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_1:
    return MongoCredential.createScramSha1Credential(username, authDatabase,
        password.toCharArray());
  case GSSAPI:
    return MongoCredential.createGSSAPICredential(username);
  case MONGODB_CR:
    return MongoCredential.createMongoCRCredential(username, authDatabase,
        password.toCharArray());
  case MONGODB_X509:
    return MongoCredential.createMongoX509Credential(username);
  }
  throw new IllegalArgumentException("Unsupported authentication mechanism "
      + authMechanismName);
}
 
Example 2
Source File: DefaultHygieiaServiceImpl.java    From ExecDashboard with Apache License 2.0 6 votes vote down vote up
@Override
public MongoClient getMongoClient(BunitCredentials bunitCredential) {
	try {
		if (bunitCredential != null) {
			ServerAddress serverAddr = new ServerAddress(bunitCredential.getHost(), bunitCredential.getPort());

			MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
					bunitCredential.getDbUserName(), bunitCredential.getDbName(),
					bunitCredential.getDbUserCredentials().toCharArray());
			MongoClient client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential));
			return client;
		}
	} catch (Exception e) {
		LOG.error(e.getMessage());
	}
	return null;
}
 
Example 3
Source File: MongoTransactionOperateRepository.java    From Lottor with MIT License 6 votes vote down vote up
/**
 * 生成mongoClientFacotryBean
 *
 * @param config 配置信息
 * @return bean
 */
private MongoClientFactoryBean buildMongoClientFactoryBean(TxMongoConfig config) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
            config.getMongoDbName(),
            config.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{
            credential
    });
    List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
    final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
            .map(url -> {
                List<String> adds = Splitter.on(":").trimResults().splitToList(url);
                return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
            }).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);

    clientFactoryBean.setReplicaSetSeeds(serverAddresses);
    return clientFactoryBean;
}
 
Example 4
Source File: MongoConfig.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {
    //创建客户端参数
    MongoClientOptions options = mongoClientOptions(properties);

    //创建客户端和Factory
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : properties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }

    //创建认证客户端
    MongoCredential mongoCredential = MongoCredential
            .createScramSha1Credential(
                    properties.getUsername(),
                    properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                    properties.getPassword().toCharArray()
            );
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, options);

    return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
}
 
Example 5
Source File: MongoTransactionRecoverRepository.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final TxMongoConfig config) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
            config.getMongoDbName(),
            config.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});
    List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
    final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
            .map(url -> {
                List<String> adds = Splitter.on(":").trimResults().splitToList(url);
                return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
            }).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);

    clientFactoryBean.setReplicaSetSeeds(serverAddresses);
    return clientFactoryBean;
}
 
Example 6
Source File: MongoCoordinatorRepository.java    From hmily with Apache License 2.0 6 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final HmilyMongoConfig hmilyMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(hmilyMongoConfig.getMongoUserName(),
            hmilyMongoConfig.getMongoDbName(),
            hmilyMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});

    List<String> urls = Lists.newArrayList(Splitter.on(",").trimResults().split(hmilyMongoConfig.getMongoDbUrl()));
    ServerAddress[] sds = new ServerAddress[urls.size()];
    for (int i = 0; i < sds.length; i++) {
        List<String> adds = Lists.newArrayList(Splitter.on(":").trimResults().split(urls.get(i)));
        InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
        sds[i] = new ServerAddress(address);
    }
    clientFactoryBean.setReplicaSetSeeds(sds);
    return clientFactoryBean;
}
 
Example 7
Source File: MongoConfiguration.java    From mongolastic with MIT License 6 votes vote down vote up
private MongoCredential findMongoCredential(String user, String database, char[] pwd, String mechanism) {
    MongoCredential credential = null;
    switch (mechanism) {
        case "scram-sha-1":
            credential = MongoCredential.createScramSha1Credential(user, database, pwd);
            break;
        case "x509":
            credential = MongoCredential.createMongoX509Credential(user);
            break;
        case "cr":
            credential = MongoCredential.createMongoCRCredential(user, database, pwd);
            break;
        case "plain":
            credential = MongoCredential.createPlainCredential(user, database, pwd);
            break;
        case "gssapi":
            credential = MongoCredential.createGSSAPICredential(user);
            break;
        default:
            credential = MongoCredential.createCredential(user, database, pwd);
            break;
    }
    return credential;
}
 
Example 8
Source File: MongoClientWrapper.java    From mongowp with Apache License 2.0 6 votes vote down vote up
private MongoCredential toMongoCredential(MongoAuthenticationConfiguration authConfiguration) {
  switch (authConfiguration.getMechanism()) {
    case cr:
      return MongoCredential.createMongoCRCredential(authConfiguration.getUser(),
          authConfiguration.getSource(), authConfiguration.getPassword().toCharArray());
    case scram_sha1:
      return MongoCredential.createScramSha1Credential(authConfiguration.getUser(),
          authConfiguration.getSource(), authConfiguration.getPassword().toCharArray());
    case negotiate:
      return MongoCredential.createCredential(authConfiguration.getUser(), authConfiguration
          .getSource(), authConfiguration.getPassword().toCharArray());
    case x509:
      return MongoCredential.createMongoX509Credential(authConfiguration.getUser());
    default:
      throw new UnsupportedOperationException("Authentication mechanism " + authConfiguration
          .getMechanism() + " not supported");
  }
}
 
Example 9
Source File: MongoSchemaFactory.java    From calcite with Apache License 2.0 6 votes vote down vote up
private MongoCredential createCredential(Map<String, Object> map) {
  final String authMechanismName = (String) map.get("authMechanism");
  final AuthenticationMechanism authenticationMechanism =
      AuthenticationMechanism.fromMechanismName(authMechanismName);
  final String username = (String) map.get("username");
  final String authDatabase = (String) map.get("authDatabase");
  final String password = (String) map.get("password");

  switch (authenticationMechanism) {
  case PLAIN:
    return MongoCredential.createPlainCredential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_1:
    return MongoCredential.createScramSha1Credential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_256:
    return MongoCredential.createScramSha256Credential(username, authDatabase,
        password.toCharArray());
  case GSSAPI:
    return MongoCredential.createGSSAPICredential(username);
  case MONGODB_X509:
    return MongoCredential.createMongoX509Credential(username);
  }
  throw new IllegalArgumentException("Unsupported authentication mechanism "
      + authMechanismName);
}
 
Example 10
Source File: MongoConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private MongoCredential createCredential(Map<String, String> properties) throws DataServiceFault {
    MongoCredential credential = null;
    String authenticationType = properties.get(DBConstants.MongoDB.AUTHENTICATION_TYPE);
    String username = properties.get(DBConstants.MongoDB.USERNAME);
    String password = properties.get(DBConstants.MongoDB.PASSWORD);
    String database = properties.get(DBConstants.MongoDB.DATABASE);
    if (authenticationType != null) {
        switch (authenticationType) {
            case DBConstants.MongoDB.MongoAuthenticationTypes.PLAIN:
                credential = MongoCredential.createPlainCredential(username, database, password.toCharArray());
                break;
            case DBConstants.MongoDB.MongoAuthenticationTypes.SCRAM_SHA_1:
                credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
                break;
            case DBConstants.MongoDB.MongoAuthenticationTypes.MONGODB_CR:
                credential = MongoCredential.createMongoCRCredential(username, database, password.toCharArray());
                break;
            case DBConstants.MongoDB.MongoAuthenticationTypes.GSSAPI:
                credential = MongoCredential.createGSSAPICredential(username);
                break;
            case DBConstants.MongoDB.MongoAuthenticationTypes.MONGODB_X509:
                credential = MongoCredential.createMongoX509Credential(username);
                break;
            default:
                throw new DataServiceFault("Invalid Authentication type. ");
        }
        return credential;
    } else {
        return null;
    }
}
 
Example 11
Source File: MongoDBFactory.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * @decription 初始化配置
 * @author yi.zhang
 * @time 2017年6月2日 下午2:15:57
 */
public void init(String servers,String database,String schema,String username,String password) {
	try {
		List<ServerAddress> saddress = new ArrayList<ServerAddress>();
		if (servers != null && !"".equals(servers)) {
			for (String server : servers.split(",")) {
				String[] address = server.split(":");
				String ip = address[0];
				int port = 27017;
				if (address != null && address.length > 1) {
					port = Integer.valueOf(address[1]);
				}
				saddress.add(new ServerAddress(ip, port));
			}
		}
		MongoCredential credential = MongoCredential.createScramSha1Credential(username, database,password.toCharArray());
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		credentials.add(credential);
		Builder builder = new MongoClientOptions.Builder();
		builder.maxWaitTime(MAX_WAIT_TIME);
		// 通过连接认证获取MongoDB连接
		MongoClient client = new MongoClient(saddress, credentials, builder.build());
		// 连接到数据库
		session = client.getDatabase(schema);
	} catch (Exception e) {
		logger.error("-----MongoDB Config init Error-----", e);
	}
}
 
Example 12
Source File: MongoCoordinatorRepository.java    From myth with Apache License 2.0 5 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final MythMongoConfig mythMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(mythMongoConfig.getMongoUserName(),
            mythMongoConfig.getMongoDbName(),
            mythMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});
    List<String> urls = Splitter.on(",").trimResults().splitToList(mythMongoConfig.getMongoDbUrl());
    final ServerAddress[] sds = urls.stream().map(url -> {
        List<String> adds = Splitter.on(":").trimResults().splitToList(url);
        InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
        return new ServerAddress(address);
    }).collect(Collectors.toList()).toArray(new ServerAddress[]{});
    clientFactoryBean.setReplicaSetSeeds(sds);
    return clientFactoryBean;
}
 
Example 13
Source File: MongoConfig.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClient legacyMongoClient() {
	final CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
			fromProviders(PojoCodecProvider.builder().automatic(true).build()));
	final MongoClientOptions options = MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build();

	final MongoCredential credentials = MongoCredential.createScramSha1Credential(this.username, "admin", this.password.toCharArray());
	return new MongoClient(new ServerAddress(this.host, NumberUtils.toInt(this.port)), credentials, options);
}
 
Example 14
Source File: MongoClients.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private MongoCredential createMongoCredential(MongoClientConfig config) {
    String username = config.credentials.username.orElse(null);
    if (username == null) {
        return null;
    }

    char[] password = config.credentials.password.map(String::toCharArray).orElse(null);
    // get the authsource, or the database from the config, or 'admin' as it is the default auth source in mongo
    // and null is not allowed
    String authSource = config.credentials.authSource.orElse(config.database.orElse("admin"));
    // AuthMechanism
    AuthenticationMechanism mechanism = null;
    Optional<String> maybeMechanism = config.credentials.authMechanism;
    if (maybeMechanism.isPresent()) {
        mechanism = getAuthenticationMechanism(maybeMechanism.get());
    }

    // Create the MongoCredential instance.
    MongoCredential credential;
    if (mechanism == GSSAPI) {
        credential = MongoCredential.createGSSAPICredential(username);
    } else if (mechanism == PLAIN) {
        credential = MongoCredential.createPlainCredential(username, authSource, password);
    } else if (mechanism == MONGODB_X509) {
        credential = MongoCredential.createMongoX509Credential(username);
    } else if (mechanism == SCRAM_SHA_1) {
        credential = MongoCredential.createScramSha1Credential(username, authSource, password);
    } else if (mechanism == null) {
        credential = MongoCredential.createCredential(username, authSource, password);
    } else {
        throw new IllegalArgumentException("Unsupported authentication mechanism " + mechanism);
    }

    //add the properties
    if (!config.credentials.authMechanismProperties.isEmpty()) {
        for (Map.Entry<String, String> entry : config.credentials.authMechanismProperties.entrySet()) {
            credential = credential.withMechanismProperty(entry.getKey(), entry.getValue());
        }
    }

    return credential;
}
 
Example 15
Source File: MongoConfig.java    From cloudfoundry-service-broker with Apache License 2.0 4 votes vote down vote up
@Bean
public MongoClient mongoClient() throws UnknownHostException {
	final MongoCredential credential = MongoCredential.createScramSha1Credential(username, authSource, password.toCharArray());
	return new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
}
 
Example 16
Source File: CredentialListParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
public CredentialListParser(JsonObject config) {
  String username = config.getString("username");
  // AuthMechanism
  AuthenticationMechanism mechanism = null;
  String authMechanism = config.getString("authMechanism");
  if (authMechanism != null) {
    mechanism = getAuthenticationMechanism(authMechanism);
  }
  credentials = new ArrayList<>();
  if (username == null) {
    if (mechanism == MONGODB_X509) {
      credentials.add(MongoCredential.createMongoX509Credential());
    }
  } else {
    String passwd = config.getString("password");
    char[] password = (passwd == null) ? null : passwd.toCharArray();
    // See https://github.com/vert-x3/vertx-mongo-client/issues/46 - 'admin' as default is a security
    // concern, use  the 'db_name' if none is set.
    String authSource = config.getString("authSource",
      config.getString("db_name", MongoClientImpl.DEFAULT_DB_NAME));

    // MongoCredential
    String gssapiServiceName = config.getString("gssapiServiceName");
    MongoCredential credential;
    if (mechanism == GSSAPI) {
      credential = MongoCredential.createGSSAPICredential(username);
      credential = getMongoCredential(gssapiServiceName, credential);
    } else if (mechanism == PLAIN) {
      credential = MongoCredential.createPlainCredential(username, authSource, password);
    } else if (mechanism == MONGODB_X509) {
      credential = MongoCredential.createMongoX509Credential(username);
    } else if (mechanism == SCRAM_SHA_1) {
      credential = MongoCredential.createScramSha1Credential(username, authSource, password);
    } else if (mechanism == SCRAM_SHA_256) {
      credential = MongoCredential.createScramSha256Credential(username, authSource, password);
    } else if (mechanism == null) {
      credential = MongoCredential.createCredential(username, authSource, password);
    } else {
      throw new IllegalArgumentException("Unsupported authentication mechanism " + mechanism);
    }

    credentials.add(credential);
  }
}