Asp.Net Core Web MVC簡單Cookie登入驗證
阿新 • • 發佈:2021-08-28
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?}"); }); } }