Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1K
Visualizações
unable to authenticate with mongodb golang driver

I'm using mongodb community version 4.2.13 and go driver version 1.5.

My go application is running on the same host as db, but getting the following error when trying to make a connection:

connection() error occured during connection handshake: auth error:
sasl conversation error: unable to authenticate using mechanism
"SCRAM-SHA-256": (AuthenticationFailed) Authentication failed.

Here is how I created the admin account:

use admin
db.createUser({
  user: "admin1",
  pwd: "passwd12#$",
  roles: ["root"],
  mechanisms: ["SCRAM-SHA-256"]
})

db.system.users.update(
  { _id: "admin.admin1", "db": "admin" },
  {
    $addToSet: {
      authenticationRestrictions: { clientSource: ["127.0.0.1"] }
    }
  }
)

Go app code snippet

package main

import (
    "context"
    "fmt"
    "time"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    uri := fmt.Sprintf(
        "mongodb://%s:%s@%s:%d/admin?authSource=admin&authMechanism=SCRAM-SHA-256",
        "admin1",
        "passwd12#$",
        "127.0.0.1",
        27017,
    )
 
    // Prints "mongodb://admin1:passwd12#$@127.0.0.1:27017/admin?authSource=admin&authMechanism=SCRAM-SHA-256"
    fmt.Println(uri)
    ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
    defer cancel()
    client, err := mongo.Connect(
        ctx,
        options.Client().ApplyURI(uri),
    )
    if err != nil {
        panic(err)
    }
    defer func() {
        err = client.Disconnect(ctx)
        if err != nil {
            panic(err)
        }
    }()
    err = client.Ping(ctx, nil)
    if err != nil {
        panic(err)
    }
    fmt.Println("pinged")
}

I tried the following, but all of them didn't work:

  • Encoding username and password using url.QueryEscape
  • Trying "localhost" instead of "127.0.0.1"
  • Removing "authMechanism=SCRAM-SHA-256" in uri

As a side note, connecting to the Mongo shell with the exact same uri, and that worked.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Add ssl=false to your uri. Worked for me

over 4 years ago · Santiago Trujillo Relatório

0

You could try using 'options.Credential' to pass the authentication settings.

Seems like a cleaner way than formatting an URI that needs to be parsed later on.

https://docs.mongodb.com/drivers/go/current/fundamentals/auth/

clientOpts := options.Client().SetHosts(
    []string{"localhost:27017"},
).SetAuth(
    options.Credential{
        AuthSource: "<authenticationDb>",
        AuthMechanism: "SCRAM-SHA-256",
        Username: "<username>",
        Password: "<password>",
    }
)
client, err := mongo.Connect(context.TODO(), clientOpts)
over 4 years ago · Santiago Trujillo Relatório

0

Based on MongoDB documentation for the authentication process, there is a parameter to identify which database is used for authentication besides the target database on the URI.

While in mongoshell you can use this line

mongo "mongodb://Admin:${DBPASSWORD}@<host>:<port>/admin?authSource=admin"

I used that information to add ?authSource=admin to my CONNECTION_URL

CONNECTION_URL=mongodb://root:example@mongo:27017/my_database?retryWrites=true&w=majority&authSource=admin

That worked for me. Hope it does for you too.

For detailed information please review https://www.mongodb.com/features/mongodb-authentication

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda