How to Role based Authorization in ASP.NET Core
Let's see how we can authorize an API access based on an user role defined by the system or a user based on a claim based on the JWT token passed within the request.
What is a Role?
A Role can be assumed as a designation or an earmarking assigned to a specific user which serves a responsibility. Typical examples for Roles include:
an admin
an author
an editor or
a librarian
These roles provide certain levels of access restriction and abstraction with them, such as:
"not all users are granted access to book keeping system except the librarian"
"not all users can edit posts except the editors" and
"not all editors can delete the post schema except the admin".
These are differentiated in real-world at the authentication levels, by providing with separate logins or separate portals. We can also restrict access levels for such endpoints by passing in extra attributes for the earmarked users.
In the world of token based authentication and authorization systems, it is made further simple by making use of the ClaimType attributes provided within the ClaimsIdentity libraries. We can then configure the Authorization middleware to look for Role attributes available in the token to allow access to the decorated endpoints.
We have seen why Token based Authentication using JWT is the right way of securing API endpoints against unauthorized or unwanted access when exposed to the Internet. We have also seen how Authentication and Authorization differ from each other.
In this article let's talk about two important scenarios in which an authenticated user be authorized for API access:
Based on a Role defined by the system and
Based on a Claim value inside the user token
While these two may seem to be of different in their functionalities and usage cases, they both branch out from the Policy based authorization that the ASP.NET Core provides us with.
Read the full article here - How to Role based Authorization in ASP.NET Core