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



我有一个旧的 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. 在"启动.cs"中,配置方法。

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

    [Authorize]
    public IActionResult Index()
    {
      return View();
    }
    
  3. 在"主控制器,登录发布"操作方法中,编写以下方法。

    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已经弃用了许多类。仅供参考:

启动.cs - 在配置服务中:

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

启动.cs - 在配置中:

app.UseAuthentication();

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

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

最新更新