If you want to enable authentication on a replica set or a sharded cluster, members of the replica set or the sharded clusters must provide credentials to authenticate.
You can generate a keyfile must be between 6 and 1024 characters long.
Create --keyfile in mongos (router server)
The following command generate a keyfile using openssl with pseudo-random 1024 character string, then change the permission to provide read permission for file owner only using chmod.
# openssl rand -base64 741 > /home/mongodb/mongodb-keyfile
# chmod 600 mongodb-keyfile
Stop scaling service( shared cluster, mongos and config servers)
Enable authentication for each member of the shared cluster or replica set
For each mongod in the replica set or for each mongod and mongod in the shared cluster, including all config servers and shards, specify the keyfile using configuration file.
Open the mongoDB configure file and add below lines,
# vim /etc/mongod.conf
4. Start mongod service first then mongos services
5. To test the connection use below syntax on mongos server,
mongo --port 20170 -u "username" -p "password" --authenticationDatabase "admin"