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

The following examples show how to use com.mongodb.MongoCredential#createCredential() . 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: EmbedMongoConfiguration.java    From syndesis with Apache License 2.0 8 votes vote down vote up
private static MongoClient getClient(Boolean useCredentials, String replicaSet) {
    MongoClientSettings.Builder settings = MongoClientSettings.builder();

    if (useCredentials) {
        MongoCredential credentials = MongoCredential.createCredential(
            USER, ADMIN_DB, PASSWORD.toCharArray());
        settings.credential(credentials);
    }
    StringBuilder connectionString = new StringBuilder(String.format("mongodb://%s:%d", HOST, PORT));
    if (replicaSet != null) {
        connectionString.append(String.format("/?replicaSet=%s", REPLICA_SET));
    }
    ConnectionString uri = new ConnectionString(connectionString.toString());
    settings.applyConnectionString(uri);

    settings.readPreference(ReadPreference.primaryPreferred());

    return MongoClients.create(settings.build());
}
 
Example 2
Source File: HelperMongo.java    From helper with MIT License 6 votes vote down vote up
public HelperMongo(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    this.client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            mongoCredential,
            MongoClientOptions.builder().build()
    );
    this.database = this.client.getDatabase(credentials.getDatabase());
    this.morphia = new Morphia();
    this.morphiaDatastore = this.morphia.createDatastore(this.client, credentials.getDatabase());
    this.morphia.getMapper().getOptions().setObjectFactory(new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass() {
            return LoaderUtils.getPlugin().getClassloader();
        }
    });
}
 
Example 3
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 4
Source File: MongoAuditConfig.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Mongo mongo() throws Exception {
	if (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword())) {
		try {
			MongoCredential credential = MongoCredential.createCredential(getUsername(), getDatabaseName(), getPassword().toCharArray());
			return new MongoClient(hostname, Collections.singletonList(credential));
		} catch (Exception e) {
			return new MongoClient(hostname);
		}
	} else {
		return new MongoClient(hostname);
	}

}
 
Example 5
Source File: MongoDBUtil.java    From sockslib with Apache License 2.0 5 votes vote down vote up
private MongoClient getConnectedClient() {
  if (Strings.isEmpty(username)) {
    return new MongoClient(host, port);
  } else {
    MongoCredential credential =
        MongoCredential.createCredential(username, databaseName, password.toCharArray());
    return new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
  }
}
 
Example 6
Source File: GeoRyaSailFactory.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link MongoClient} that is connected to the configured database.
 *
 * @param mongoConf - Configures what will be connected to. (not null)
 * @throws ConfigurationRuntimeException An invalid port was provided by {@code mongoConf}.
 * @throws MongoException Couldn't connect to the MongoDB database.
 */
private static MongoClient createMongoClient(final MongoDBRdfConfiguration mongoConf) throws ConfigurationRuntimeException, MongoException {
    requireNonNull(mongoConf);
    requireNonNull(mongoConf.getMongoHostname());
    requireNonNull(mongoConf.getMongoPort());
    requireNonNull(mongoConf.getMongoDBName());

    // Connect to a running MongoDB server.
    final int port;
    try {
        port = Integer.parseInt( mongoConf.getMongoPort() );
    } catch(final NumberFormatException e) {
        throw new ConfigurationRuntimeException("Port '" + mongoConf.getMongoPort() + "' must be an integer.");
    }

    final ServerAddress server = new ServerAddress(mongoConf.getMongoHostname(), port);

    // Connect to a specific MongoDB Database if that information is provided.
    final String username = mongoConf.getMongoUser();
    final String database = mongoConf.getMongoDBName();
    final String password = mongoConf.getMongoPassword();
    if(username != null && password != null) {
        final MongoCredential cred = MongoCredential.createCredential(username, database, password.toCharArray());
        final MongoClientOptions options = new MongoClientOptions.Builder().build();
        return new MongoClient(server, cred, options);
    } else {
        return new MongoClient(server);
    }
}
 
Example 7
Source File: ReplicaSetBaseTest.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
protected void connectDBWithOptions(MongoClientOptions options){
    List<ServerAddress> serverList = new ArrayList<ServerAddress>();
    serverList.add(new ServerAddress("192.168.0.200", 27017));
    serverList.add(new ServerAddress("192.168.0.200", 27018));
    serverList.add(new ServerAddress("192.168.0.200", 27019));
    
    List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
    MongoCredential credentialA = MongoCredential.createCredential("test", "test", "test".toCharArray());
    MongoCredential credentialB = MongoCredential.createCredential("test", "test", "test".toCharArray());
    MongoCredential credentialC = MongoCredential.createCredential("test", "test", "test".toCharArray());
    credentialList.add(credentialA);
    credentialList.add(credentialB);
    credentialList.add(credentialC);
    BuguConnection conn = BuguFramework.getInstance().createConnection();
    conn.setOptions(options);
    conn.setServerList(serverList);
    conn.setCredentialList(credentialList);
    conn.setDatabase("test");
    conn.connect();
}
 
Example 8
Source File: MongoRyaSinkTask.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkRyaInstanceExists(final Map<String, String> taskConfig) throws IllegalStateException {
    requireNonNull(taskConfig);

    // Parse the configuration object.
    final MongoRyaSinkConfig config = new MongoRyaSinkConfig(taskConfig);
    @Nullable
    final String username = Strings.isNullOrEmpty(config.getUsername()) ? null : config.getUsername();
    @Nullable
    final char[] password = Strings.isNullOrEmpty(config.getPassword()) ? null : config.getPassword().toCharArray();

    // Connect a Mongo Client to the configured Mongo DB instance.
    final ServerAddress serverAddr = new ServerAddress(config.getHostname(), config.getPort());
    final boolean hasCredentials = username != null && password != null;

    final MongoClientOptions options = new MongoClientOptions.Builder().build();

    try(final MongoClient mongoClient = hasCredentials ?
            new MongoClient(serverAddr, MongoCredential.createCredential(username, config.getRyaInstanceName(), password), options) :
            new MongoClient(serverAddr)) {
        // Use a RyaClient to see if the configured instance exists.
        // Create the Mongo Connection Details that describe the Mongo DB Server we are interacting with.
        final MongoConnectionDetails connectionDetails = new MongoConnectionDetails(
                config.getHostname(),
                config.getPort(),
                Optional.ofNullable(username),
                Optional.ofNullable(password));

        final RyaClient client = MongoRyaClientFactory.build(connectionDetails, mongoClient);
        if(!client.getInstanceExists().exists( config.getRyaInstanceName() )) {
            throw new ConnectException("The Rya Instance named " +
                    LogUtils.clean(config.getRyaInstanceName()) + " has not been installed.");
        }
    } catch(final RyaClientException e) {
        throw new ConnectException("Unable to determine if the Rya Instance named " +
                LogUtils.clean(config.getRyaInstanceName()) + " has been installed.", e);
    }
}
 
Example 9
Source File: MongoConfiguration.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Bean
public MongoClient mongoClient(final MongoSettings mongoSettings) {
    ServerAddress serverAddress = new ServerAddress(
            mongoSettings.getHost(), mongoSettings.getPort());

    MongoCredential credential = MongoCredential.createCredential(
            mongoSettings.getUsername(),
            mongoSettings.getDatabase(),
            mongoSettings.getPassword().toCharArray());

    return new MongoClient(
            serverAddress, credential, new MongoClientOptions.Builder().build());
}
 
Example 10
Source File: MongoDSN.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public static MongoClient	newClient(String server, String user, String pass, String db) throws UnknownHostException{

	MongoClientOptions options = MongoClientOptions
			.builder()
			.readPreference( ReadPreference.secondaryPreferred() )
			.build();

	List<InetSocketAddress> serverList = AddrUtil.getAddresses(server);
	List<ServerAddress> addrs = new ArrayList<ServerAddress>();
		
	Iterator<InetSocketAddress>	it	= serverList.iterator();
	while ( it.hasNext() ){
		InetSocketAddress	isa	= it.next();
		addrs.add( new ServerAddress( isa.getAddress(), isa.getPort() ) );
	}
	
	
	if ( user != null ) {
		MongoCredential cred = MongoCredential.createCredential( user, db, pass.toCharArray() );
		List<MongoCredential> creds = new ArrayList<MongoCredential>();
		creds.add( cred );

		return new MongoClient( addrs, creds, options );
	} else {
		return new MongoClient( addrs, options );
	}

	
}
 
Example 11
Source File: MongoWrapper.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
private MongoCredential createCredentials(AbstractConfig config, String dbName) {
    String userName = config.getString(MONGO_USERNAME);
    String password = config.getString(MONGO_PASSWORD);
    if (isValid(userName) && isValid(password)) {
        return MongoCredential.createCredential(userName, dbName, password.toCharArray());
    } else {
        return null;
    }
}
 
Example 12
Source File: MongoStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void init() {
    if (!Strings.isNullOrEmpty(this.connectionUri)) {
        this.mongoClient = new MongoClient(new MongoClientURI(this.connectionUri));
    } else {
        MongoCredential credential = null;
        if (!Strings.isNullOrEmpty(this.configuration.getUsername())) {
            credential = MongoCredential.createCredential(
                    this.configuration.getUsername(),
                    this.configuration.getDatabase(),
                    Strings.isNullOrEmpty(this.configuration.getPassword()) ? null : this.configuration.getPassword().toCharArray()
            );
        }

        String[] addressSplit = this.configuration.getAddress().split(":");
        String host = addressSplit[0];
        int port = addressSplit.length > 1 ? Integer.parseInt(addressSplit[1]) : 27017;
        ServerAddress address = new ServerAddress(host, port);

        if (credential == null) {
            this.mongoClient = new MongoClient(address);
        } else {
            this.mongoClient = new MongoClient(address, credential, MongoClientOptions.builder().build());
        }
    }
    
    this.database = this.mongoClient.getDatabase(this.configuration.getDatabase());
}
 
Example 13
Source File: TestMongoClientConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpecialCharacterCredential()
{
    MongoClientConfig config = new MongoClientConfig()
            .setCredentials("username:P@ss:w0rd@database");

    MongoCredential credential = config.getCredentials().get(0);
    MongoCredential expected = MongoCredential.createCredential("username", "database", "P@ss:w0rd".toCharArray());
    assertEquals(credential, expected);
}
 
Example 14
Source File: JaversDedicatedMongoFactory.java    From javers with Apache License 2.0 5 votes vote down vote up
private static MongoCredential getCredentials(JaversMongoProperties properties) {
    if (!hasCustomCredentials(properties)) {
        return null;
    }
    String username = properties.getMongodb().getUsername();
    String database = properties.getMongodb().getAuthenticationDatabase() != null
            ? properties.getMongodb().getAuthenticationDatabase() : properties.getMongodb().getDatabase();
    char[] password = properties.getMongodb().getPassword();
    return MongoCredential.createCredential(username, database, password);
}
 
Example 15
Source File: KyMongoConfig.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
@Override
public MongoClient mongoClient() {
    if (DbSetting.AUTHENTICATION_STATUS) {
        return new MongoClient(
                new ServerAddress(DbSetting.MONGODB_HOST, DbSetting.MONGODB_PORT),
                MongoCredential.createCredential(DbSetting.DATABASE_USERNAME, getDatabaseName(), DbSetting.DATABASE_PASSWORD.toCharArray()),
                MongoClientOptions.builder().build()
        );
    } else {
        return new MongoClient(new ServerAddress(DbSetting.MONGODB_HOST, DbSetting.MONGODB_PORT));
    }
}
 
Example 16
Source File: MongoClientCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    MongoCustomizersUtil.replaceAdminDBIfMissing(options);
    // Set connection parameter
    if (!options.containsKey("mongoConnection")) {
        if (options.containsKey("user") && options.containsKey("password")
                && options.containsKey("host")) {
            ConnectionParamsConfiguration mongoConf = new ConnectionParamsConfiguration(cast(options));
            // We need to force consumption in order to perform property placeholder done by Camel
            consumeOption(camelContext, options, "password", String.class, mongoConf::setPassword);
            LOGGER.debug("Creating and registering a client connection to {}", mongoConf);

            MongoClientSettings.Builder settings = MongoClientSettings.builder();
            MongoCredential credentials = MongoCredential.createCredential(
                mongoConf.getUser(),
                mongoConf.getAdminDB(),
                mongoConf.getPassword().toCharArray());

            ConnectionString uri = new ConnectionString(mongoConf.getMongoClientURI());
            settings.applyConnectionString(uri);
            settings.credential(credentials);

            MongoClient mongoClient = MongoClients.create(settings.build());

            options.put("mongoConnection", mongoClient);
            if (!options.containsKey("connectionBean")) {
                //We safely put a default name instead of leaving null
                options.put("connectionBean", String.format("%s-%s", mongoConf.getHost(), mongoConf.getUser()));
            }
        } else {
            LOGGER.warn(
                "Not enough information provided to set-up the MongoDB client. Required at least host, user and " +
                    "password.");
        }
    }
}
 
Example 17
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);
  }
}
 
Example 18
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 19
Source File: DFMongoCfg.java    From dfactor with MIT License 4 votes vote down vote up
public DFMongoCfg setCredential(String dbName, String userName, String password){
	credential = MongoCredential.createCredential(userName, dbName, password.toCharArray());
	return this;
}
 
Example 20
Source File: MongodbManager.java    From grain with MIT License 3 votes vote down vote up
/**
 * 初始化mongodb
 * 
 * @param url
 *            地址
 * @param port
 *            端口
 * @param username
 *            用户名
 * @param password
 *            密码
 * @param dbName
 *            数据库名
 * @param log
 *            日志可以为null
 */
public static void init(String url, int port, String username, String password, String dbName, ILog log) {
	MongodbManager.URL = url;
	MongodbManager.PORT = port;
	MongodbManager.USERNAME = username;
	MongodbManager.PASSWORD = password;
	MongodbManager.DBNAME = dbName;
	MongodbManager.log = log;
	MongoCredential mongoCredential = MongoCredential.createCredential(username, dbName, password.toCharArray());
	mongoClient = new MongoClient(new ServerAddress(url, port), Arrays.asList(mongoCredential));
	mongoDatabase = mongoClient.getDatabase(MongodbManager.DBNAME);
}