While attempting to establish a MongoDB connection in GoLang using the mgo package, many users encounter the perplexing error message "server returned error on SASL authentication step: Authentication failed." This error can be frustrating, especially if the provided username, password, host address, and database name are known to be correct. To resolve this issue, it's crucial to consider the following solution.
Solution: Adding the authenticationDatabase Parameter
Certain MongoDB setups require the inclusion of the --authenticationDatabase parameter when establishing a connection. This parameter specifies the database to use for authentication purposes. By default, MongoDB uses the same database name as the one you are connecting to. However, in some cases, the authentication database may be different.
To resolve the error, modify the provided GoLang code to include the authenticationDatabase parameter as seen below:
mongoDialInfo: = & mgo.DialInfo { Addrs: [] string { dbHost }, Database: dbName, Username: userName, Password: password, AuthenticationDatabase: "admin", // Change this to the appropriate authentication database Timeout: 60 * time.Second, }
Ensure that the AuthenticationDatabase value matches the correct database used for authentication within your MongoDB setup. By implementing this change, you should be able to successfully connect to your MongoDB database and avoid the "Authentication failed" error.
The above is the detailed content of Why Does My GoLang MongoDB Connection Fail with 'Authentication Failed'?. For more information, please follow other related articles on the PHP Chinese website!