Asp.Net 核心 - 最简单的表单身份验证

Asp.Net Core - simplest possible forms authentication

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

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="30">
    <credentials passwordFormat="Clear">
      <user name="some-user" password="some-password" />
    </credentials>
  </forms>
</authentication>

登录例程只是调用

FormsAuthentication.Authenticate(name, password);

就是这样。 asp.net 核心是否有类似的东西(就简单性而言)?

没那么简单:)

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

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

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

    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 存储库:https://github.com/anuraj/CookieAuthMVCSample

添加到 Anuraj 的回答中 - 许多 类 已被 .Net Core 2 弃用。仅供参考:

Startup.cs - 在配置服务中:

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

Startup.cs - 在配置中:

app.UseAuthentication();

在您的 account/login 控制器中 method/wherever 您正在进行身份验证:

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