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

问题描述 投票:0回答:3
c# asp.net-mvc asp.net-core forms-authentication
3个回答
42
投票

事情没那么简单:)

  1. 在Startup.cs中,configure方法。

    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 操作方法中,编写以下方法。

    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


36
投票

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

Startup.cs - 在配置服务中:

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


0
投票

Anuraj 的回答对 MVC ASP.NET Core 6 进行了一些更新... (.net core 5 答案在 .net core 6 中不再有效)

  1. 在Program.cs中,configure方法。

    // 表单验证 builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => o.LoginPath = new PathString("/Home/Login"));

    ...

    //表单认证

    app.UseAuthentication();

  2. 添加授权属性以保护您想要保护的资源。

    [授权] 公共 IActionResult 索引() { 返回视图(); }

  3. 在 Home Controller 的 Login Post 操作方法中,编写 以下方法。

    var 用户名=配置[“用户名”];

    var 密码 = 配置[“密码”];

    if (authUser.用户名 == 用户名 && authUser.密码 == 密码) {

    var Claims = new[] { new Claim(ClaimTypes.Name, 用户名) };

    var 身份=新的ClaimsIdentity(声明, CookieAuthenticationDefaults.AuthenticationScheme);

    HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, 新的 ClaimsPrincipal(身份));

    return Redirect("~/Home/Index"); }

    否则

    {

    ModelState.AddModelError("","登录失败,请检查用户名和/或密码");

    }

© www.soinside.com 2019 - 2024. All rights reserved.