Asp.Net Core – 最简单的表单身份validation

我有这个旧的MVC5应用程序,它以最简单的forms使用表单身份validation。 web.config中只存储一个帐户,没有角色等。

       

登录例程只是调用

 FormsAuthentication.Authenticate(name, password); 

就是这样。 在asp.net核心中是否有类似的东西(在简单性方面)?

它不是那么简单:)

  1. 在Startup.cs中,配置方法。

     app.UseCookieAuthentication(options => { options.AutomaticAuthenticate = true; options.AutomaticChallenge = true; options.LoginPath = "/Home/Login"; }); 
  2. 添加Authorize属性以保护您要保护的资源。

     [Authorize] public IActionResult Index() { return View(); } 
  3. 在Home Controller,Login Post操作方法中,编写以下方法。

     var username = Configuration["username"]; var password = Configuration["password"]; if (authUser.Username == username && authUser.Password == password) { var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.Authentication.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Redirect("~/Home/Index"); } else { ModelState.AddModelError("","Login failed. Please check Username and/or password"); } 

以下是github repo供您参考: https : //github.com/anuraj/CookieAuthMVCSample

要添加到Anuraj的答案 – 已经弃用了许多类.Net Core 2.FYI:

Startup.cs – 在ConfigureServices中:

 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => o.LoginPath = new PathString("/account/login")); 

Startup.cs – 在配置中:

 app.UseAuthentication(); 

在您的帐户/登录控制器方法/您进行身份validation的任何地方:

 var claims = new[] { new Claim(ClaimTypes.Name, "MyUserNameOrID"), new Claim(ClaimTypes.Role, "SomeRoleName") }; var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await context.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); // Do your redirect here 

资料来源: https : //github.com/aspnet/Announcements/issues/232

https://github.com/aspnet/Security/issues/1310

花了好几个小时试图遵循.Net中的“新”身份范例…感谢上帝,仍然有’旧的’System.Web.Security类。 在我看来,dependency injection的使用否定了设置简单断点的能力。 或者我错过了什么。