MongoDB 添加用户名和密码

MongoDB 添加用户名和密码

我用的是 mongodb3.6,如果没有的话先安装.

sudo apt install mongodb

终端输入mongo,首先添加管理用户,

show dbs // 显示所有的数据库
use admin // 切换到admin
db.createUser({user:'root',pwd:'root',roles:['userAdminAnyDatabase']})
db.auth('root','root')

再切换数据库,添加用户,

use test
db.createUser({user:'root',pwd:'root',roles:['readWrite']})

这里写图片描述

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例代码: 首先,需要安装MongoDB的官方C#驱动程序 MongoDB.Driver。可以在Visual Studio的NuGet包管理器中搜索并安装该驱动程序。 然后,创一个ASP.NET Core Web应用程序,并在Startup.cs的ConfigureServices方法中添加MongoDB的连接字符串和数据库名称: ```csharp using Microsoft.Extensions.Configuration; using MongoDB.Driver; public class Startup { private readonly IConfiguration _config; public Startup(IConfiguration configuration) { _config = configuration; } public void ConfigureServices(IServiceCollection services) { // 添加MongoDB的连接字符串和数据库名称 var connectionString = _config.GetConnectionString("MongoDB"); var databaseName = _config.GetValue<string>("DatabaseName"); // 注册MongoDB的客户端对象 var client = new MongoClient(connectionString); services.AddSingleton<IMongoClient>(client); // 注册MongoDB的数据库对象 var database = client.GetDatabase(databaseName); services.AddSingleton(database); // 注册ASP.NET Core的身份验证服务 services.AddAuthentication("MyAuthenticationScheme") .AddCookie("MyAuthenticationScheme", options => { options.LoginPath = "/Account/Login"; }); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } ``` 其中,MongoDB的连接字符串和数据库名称可以从appsettings.json文件中读取: ```json { "ConnectionStrings": { "MongoDB": "mongodb://localhost:27017" }, "DatabaseName": "MyDatabase" } ``` 接着,创一个AccountController,并添加一个Login方法用于处理登录请求: ```csharp using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; public class AccountController : Controller { private readonly IMongoDatabase _database; public AccountController(IMongoDatabase database) { _database = database; } [HttpGet] [AllowAnonymous] public IActionResult Login() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(string username, string password) { // 查询数据库中是否存在该用户 var users = _database.GetCollection<User>("Users"); var user = await users.Find(u => u.Username == username && u.Password == password).SingleOrDefaultAsync(); if (user == null) { // 验证失败,显示错误信息 ModelState.AddModelError(string.Empty, "Username or password is incorrect."); return View(); } // 验证成功,创身份验证Cookie并跳转到新页面 var claims = new[] { new Claim(ClaimTypes.Name, user.Username) }; var identity = new ClaimsIdentity(claims, "MyAuthenticationScheme"); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return RedirectToAction("NewPage"); } [HttpGet] [Authorize(AuthenticationSchemes = "MyAuthenticationScheme")] public IActionResult NewPage() { return View(); } } public class User { public string Username { get; set; } public string Password { get; set; } } ``` 其中,User类表示用户对象,在数据库中存储每个用户的用户名密码。 在登录方法中,首先使用MongoDB的Find方法查询数据库中是否存在该用户。如果存在,则创身份验证Cookie并跳转到新页面;否则,在模型状态中添加错误信息并返回登录界面。 在NewPage方法中,使用Authorize特性指定只有经过身份验证的用户才能访问该页面。 最后,创一个Login.cshtml视图文件用于显示登录界面,并使用Bootstrap样式美化界面: ```html @model object <!DOCTYPE html> <html> <head> <title>Login</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" /> </head> <body> <div class="container"> <h1>Login</h1> <hr /> <form method="post" asp-action="Login" asp-controller="Account"> <div asp-validation-summary="All" class="alert alert-danger"></div> <div class="form-group"> <label for="username">Username:</label> <input type="text" name="username" class="form-control" /> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" name="password" class="form-control" /> </div> <button type="submit" class="btn btn-primary">Login</button> </form> </div> </body> </html> ``` 在appsettings.json文件中,添加以下配置信息: ```json { "ConnectionStrings": { "MongoDB": "mongodb://localhost:27017" }, "DatabaseName": "MyDatabase" } ``` 最后,运行应用程序并在浏览器中访问登录界面(例如,http://localhost:5000/Account/Login)。输入正确的用户名密码,即可跳转到新页面(例如,http://localhost:5000/Account/NewPage)。如果输入错误的用户名密码,则会显示验证失败的错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值