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

Pel*_*lle 27 c# asp.net-mvc forms-authentication asp.net-core

我有这个旧的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>
Run Code Online (Sandbox Code Playgroud)

登录例程只是调用

FormsAuthentication.Authenticate(name, password);
Run Code Online (Sandbox Code Playgroud)

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

Anu*_*raj 29

它不是那么简单:)

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

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

    [Authorize]
    public IActionResult Index()
    {
      return View();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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");
    }
    
    Run Code Online (Sandbox Code Playgroud)

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


And*_*yP9 18

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

Startup.cs - 在ConfigureServices中:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o => o.LoginPath = new PathString("/account/login"));
Run Code Online (Sandbox Code Playgroud)

Startup.cs - 在配置中:

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

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