Authentication through ASP.NET Core Identity and Role Based Authorization to a simple Student Registration App(ASP.NET Core 2.0, Visual Studio 2017)
ASP.NET Core Identity is a membership system which allows you to add login functionality to your application. Users can create an account and login with a user name and password or they can use an external login provider such as Facebook, Google, Microsoft Account, Twitter or others.
You can configure ASP.NET Core Identity to use a SQL Server database to store user names, passwords, and profile data. Alternatively, you can use your own persistent store, for example Azure Table Storage.
To add register and login functionalities to the application for a user using ASP.NET Core Identity, you have to make sure that when creating a new application you have changed it’s authentication to “Individual User Accounts”.
Now ASP.NET Core Identity has given register and login capabilities to an user. Now when a user is registered that user is stored in the AspNetUsers table of the newly created application’s database in MS SQL Server. (If you MS SQL Server as the database management system.)
Now you have to authorize the users according to the roles they play in the application. Consider a simple Student Registration System. In that consider the simple scenario “a student registers to a course”. Admin should be able to add, edit, delete, view an enrollment of a student. Also he should be able to add, edit the grade for a particular student to a particular course. But a student should only be able to enroll to a particular course and to view his grade. So basically in this there are only 2 roles as Admin and Student. Since the frequent user role is the “Student”, we’ll see how to authorize “Student” role to an user.
First make sure whether the Identity service is added in the ConfigureServices method in the Startup.cs class.
Then add the following highlighted code segments in the AccountController.cs class.
Then create the Student role if it is not created before the current user and assign the role to the current user. If the role is created before just assign the role to the current user. Since the role has to be assigned to the user when the user is registered the following highlighted code segment has to be added in the Register action in the AccountController.cs class.
Then authorize the action according to the roles. Following is the code snippet for authorizing the action of creating a new student and adding it to the database. For this action both Admin and Student role permissions have been granted.