Asp.Net Core Web MVC简单Cookie登录验证
1、新建Asp.Net Core Web MVC项目
2、项目目录结构
3、修改launchSettings.json
{ "profiles": { "WebApplication1": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
4、添加User.cs
public class User { public string Name { get; set; } public string Password { get; set; } }
5、添加UserServer.cs
public class UserServer { private List<User> users; public List<User> Users { get { return users; } } public UserServer() { users = new List<User>() { new User(){ Name="qqqq",Password="123"}, new User(){ Name="wwww",Password="123"}, new User(){ Name="eeee",Password="123"}, new User(){ Name="rrrr",Password="123"}, }; } }
6、Views文件夹下添加Login文件夹,添加Index.cshtml,Deny.cshtml
@{ ViewData["Title"] = "登录页面"; } <div> 请登录! </div> @using (Html.BeginForm("Login", "Login", FormMethod.Post)) { <div> <label> 用户名:</label> <input name="UserName" type="text" placeholder="请输入用户名" /> </div> <div> <label>密码:</label> <input name="Password" type="password" /> </div> <div> <input type="submit" value="登录" /> </div> } <div> @ViewBag.Msg </div>
@{ ViewData["Title"] = "未授权"; } <div> 未授权 </div>
7、添加LoginController.cs
public class LoginController : Controller { UserServer userServer = new UserServer(); public IActionResult Index() { return View(); } public async Task<IActionResult> Login() { var userName = Request.Form["UserName"]; var password = Request.Form["Password"]; var item = userServer.Users.Find(_ => _.Name == userName); if (item != null && password == item.Password) { //用Claim来构造一个ClaimsIdentity,然后调用 SignInAsync 方法。 var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, userName)); var claimsIdentity = new ClaimsIdentity(claims, "myCookies"); //登录 await HttpContext.SignInAsync("myCookies", new ClaimsPrincipal(claimsIdentity)); return RedirectToAction("Privacy", "Home"); } else ViewBag.Msg = "登陆失败"; return View("Index"); } public async Task<IActionResult> Logout() { //退出 await HttpContext.SignOutAsync("myCookies"); return RedirectToAction("Index", "Home"); } public IActionResult Deny() { return View(); } }
8、修改_Layout.cshtml
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </li> @if (User.Identity.IsAuthenticated) { <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="Logout">退出</a> </li> } </ul> </div>
9、修改Startup.cs
public class Startup { private const string cookieScheme = "myCookies"; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddAuthentication(cookieScheme) .AddCookie(cookieScheme, option => { option.LoginPath = new PathString("/login/index"); option.AccessDeniedPath = new PathString("/login/deny"); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }