Example how to create a project asp.NET CORE 2.2. with Identity and user role
In the first step create in Visual Studio 2019 a New ASP.NEt Web Application with Autentication - Individual User Account.
We want to be able to modify the source code of login, registration forms, etc. Therefore, we will add the creation of the identity framework. We will transfer the database to App_Data folder. Open file 'appsettings.json' and change in "ConnectionStrings": {"DefaultConnection": .... as described in here
In the third step we will:
-
add a technical user with Admin privileges in the file "appsettings.json" with an overt password - do not forget to change it. Preferably use "dotnet user-secrets" in own project. Use cmd and command:
dotnet user-secrets set AdminUserPW [Password]
and use variable AdminUserPw in the project:
var AdminUserPw = config ["AdminUserPW"];
-
add class SeedUserRole in file located in: Model/SeedUserRole.cs which adds Admin, Manager and Employee roles and user Admin from "appsettings.json" to the project as shown in code on branch Step3
Now you can use
[AllowAnonymous]
public IActionResult Index()
{
//...
}
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
//....
}