Authentication With ASP.NET Core Identity

发布时间 2023-07-13 14:54:55作者: ChuckLu

Authentication With ASP.NET Core Identity、

Preparing the Authentication Environment in our Project

The first thing, we are going to do is disable unauthorized users to access the Employees action. To do that, we have to add the [Authorize] attribute on top of that action:

[Authorize]
public async Task<IActionResult> Employees()
{
    var employees = await _context.Employees.ToListAsync();
    return View(employees);
}

Additionally, we have to add authentication middleware to the ASP.NET Core’s pipeline right above the app.UseAuthorization() expression:

app.UseAuthentication();

If we run our application now and click on the Employees link, we are going to get a 404 not found response:

 

We get this because, by default, ASP.NET Core Identity tries to redirect an unauthorized user to the /Account/Login action, which doesn’t exist at the moment. Additionally, you can see a ReturnUrl query string that provides a path to the required action before the user was redirected to the Login page. We are going to deal with it later in this post.

 

Now, we are going to do a couple of things to fix this 404 error.