1

I have a complete ASP.NET Core MVC application and a database that has users and roles already added. User registration is handled externally and I just need to provide authentication and authorization to the ASP.NET Core MVC app I am building for users already in the database.

What's the best way to do that?

I've tried setting up Identity and connecting it to the user/role database via Entity Framework, but it seems like overkill and the setup has been overwhelming. Any recommendations on the simplest way accomplish this?

I've looked at this question, but a lot of it doesn't seem to apply to ASP.NET Core MVC ...

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
bx ded
  • 49
  • 6

1 Answers1

5

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.

Fei Han
  • 26,415
  • 1
  • 30
  • 41