在 ASP.NET Core MVC 应用程序中使用已具有用户和角色的数据库设置/处理身份验证的最简单方法

bx *_*ded 1 c# authentication authorization asp.net-core-mvc

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

最好的方法是什么?

我尝试过设置身份并通过实体框架将其连接到用户/角色数据库,但这似乎有点矫枉过正,而且设置已经势不可挡。关于最简单的方法有什么建议可以实现这一点吗?

我已经看过这个问题,但其中很多似乎不适用于 ASP.NET Core MVC ...

谢谢!

Fei*_*Han 5

需要为我正在为数据库中已有的用户构建的 ASP.NET Core MVC 应用程序提供身份验证和授权

正如您所提到的,您已经在数据库中拥有users包含roles记录的相关表,为了在 ASP.NET Core MVC 应用程序中实现/集成身份验证功能,您可以尝试使用基于 cookie 的身份验证提供程序,而无需 ASP.NET Core Identity。

身份验证的服务配置

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

动作方法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;
    }
Run Code Online (Sandbox Code Playgroud)

该文档带有示例解释了如何在不使用 ASP.NET Core Identity 的情况下实现 cookie 身份验证,您可以参考它。