在 ASP.NET 核心 MVC 应用程序中设置 up/handle 身份验证的最简单方法,数据库已具有用户和角色

Easiest way to set up/handle authentication in ASP.NET Core MVC application with database that already has users and roles

我有一个完整的 ASP.NET 核心 MVC 应用程序和一个已经添加了用户和角色的数据库。用户注册是在外部处理的,我只需要为我正在为数据库中已有的用户构建的 ASP.NET 核心 MVC 应用程序提供身份验证和授权。

最好的方法是什么?

我已经尝试设置 Identity 并通过 Entity Framework 将其连接到 user/role 数据库,但这似乎有点矫枉过正,而且设置非常繁琐。有没有关于完成此操作的最简单方法的建议?

我看过 ,但其中很多内容似乎不适用于 ASP.NET Core MVC ...

谢谢!

need to provide authentication and authorization to the ASP.NET Core MVC app I am building for users already in the database

正如您所提到的,您的数据库中已经有 usersroles 相关表,以及 ASP.NET 核心 MVC 应用程序中的 implement/integrate 身份验证功能,您可以尝试使用没有 ASP.NET Core Identity 的基于 cookie 的身份验证提供程序。

认证服务配置

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
    options.LoginPath = "/Account/Login/";
    //...
    options.ExpireTimeSpan = TimeSpan.FromDays(7);
    options.Cookie.Name = "authcookie";
});

操作方法Login

[HttpPost]
public async Task<IActionResult> Login(LoginModel loginModel)
{
    if (LoginUser(loginModel.Username, loginModel.Password))
    {
        var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, loginModel.Username)
    };

        var userIdentity = new ClaimsIdentity(claims, "login");

        ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
        await HttpContext.SignInAsync(principal);

        //Just redirect to our index after logging in. 
        return Redirect("/");
    }
    return View();
}

    private bool LoginUser(string username, string password)
    {
        //code logic here 
        //check record from your database

        //... 
        return true;
    }

This doc 有示例解释了在没有 ASP.NET Core Identity 的情况下实现 cookie 身份验证,您可以参考它。