【问题标题】:Asp.Net Core - simplest possible forms authenticationAsp.Net Core - 最简单的表单身份验证
【发布时间】:2017-05-17 07:25:09
【问题描述】:

我有这个旧的 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 core 中是否有类似的东西(就简单性而言)?

【问题讨论】:

  • 使用 FormAuth 进行身份验证与 asp.net 核心不兼容。而是使用身份

标签: c# asp.net-mvc asp.net-core forms-authentication


【解决方案1】:

没那么简单:)

  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 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

【讨论】:

【解决方案2】:

补充 Anuraj 的答案 - .Net Core 2 已弃用许多类。仅供参考:

Startup.cs - 在 ConfigureServices 中:

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

Startup.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

【讨论】:

  • 在使用 jwt 和 cookie 进行双重身份验证时循环回登录表单时遇到问题。结果从 await context.SignInAsync(new ClaimsPrincipal(identity));等待 context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));成功了。谢谢@AndyP9!
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 2011-03-05
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多