2
respostas

Erro de autenticação

@Repository
public class AlunoRepository {

    public void salvar(Aluno aluno) {

        Codec<Document> codec = MongoClient.getDefaultCodecRegistry().get(Document.class);
        AlunoCodec alunoCodec = new AlunoCodec(codec);

        CodecRegistry registro = CodecRegistries.fromRegistries(
            MongoClient.getDefaultCodecRegistry(), 
            CodecRegistries.fromCodecs(alunoCodec));

        MongoClientOptions options = MongoClientOptions.builder().codecRegistry(registro).build();
        String str = "Mongo10";
        char[] ch = str.toCharArray();        


        MongoCredential credential = MongoCredential.createCredential("test", "mongo", ch);
        MongoClient cliente = new MongoClient( new ServerAddress("localhost"), credential, options);
        MongoDatabase bancoDeDados = cliente.getDatabase("test");
        MongoCollection<Aluno> alunos = bancoDeDados.getCollection("alunos", Aluno.class);

        alunos.insertOne(aluno);
        cliente.close();
    }

}
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='test', source='mongo', password=<hidden>, mechanismProperties=<hidden>}] with root cause

com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
    at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175) ~[mongo-java-driver-3.12.8.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:302) ~[mongo-java-driver-3.12.8.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:258) ~[mongo-java-driver-3.12.8.jar:na]
2 respostas

Oi Bruno,

cliente.getDatabase("test");

essa database "test" existe no seu MongoDB?

Sim, confirmei.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software