need to provide authentication and authorization to the ASP.NET Core MVC app I am building for users already in the database
As you mentioned, you already have users
and roles
related tables with records in your database, to implement/integrate authentication functionality in your ASP.NET Core MVC app, you can try to use cookie-based authentication provider without ASP.NET Core Identity.
Service configuration for authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = "/Account/Login/";
//...
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.Cookie.Name = "authcookie";
});
Action method 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 with sample explained about implement cookie authentication without ASP.NET Core Identity, you can refer to it.