Do not use roles in your API, use this instead
<p>Why should you ever use built-in role-based authorization in your API?</p>
<pre>
[HttpGet("get_something")]
[Authorize(Role = "admin, admins_cat")]
[Authorize(Role = "hacker")]
public Task<IActionResult> GetSomething()</pre>
<p>Okay, it looks nice and works well, but in the case of a big SaaS application, you lose some flexibility. Let’s imagine, you have 3 main roles: StandartUser, PremiumUser, and EnterpriseUser. You have written a lot of functionality, and hundreds of endpoints. And this is the time to extend your subscription list. You want to add UltraUser role, such a user would have full access to all functionality. So now you should put this all over your application.</p>
<pre>
[Authorize(Role = "UltraUser")]</pre>
<p>I prefer to use enum flags for roles, permissions, and so on. Let’s dive deeper into this theme.</p>
<p>We are creating a new PermissionEnum with all of the features our application gives the user. For example, we have: Add, Update, Delete, Get, and Special features. It would look like this.</p>
<pre>
[Flags]
public enum PermissionEnum : int
{
None = 0,
Add = 1,
Update = 1 << 1,
Delete = 1 << 2,
Get = 1 << 3,
Special = 1 << 4
}</pre>
<p>If you are not familiar with enum flags, you should take some time to read this:</p>
<h2><a href="https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=net-7.0&source=post_page-----c7b14deba1fb--------------------------------" rel="noopener ugc nofollow" target="_blank">FlagsAttribute Class (System)</a></h2>
<h3><a href="https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=net-7.0&source=post_page-----c7b14deba1fb--------------------------------" rel="noopener ugc nofollow" target="_blank">Indicates that an enumeration can be treated as a bit field; that is, a set of flags.</a></h3>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=net-7.0&source=post_page-----c7b14deba1fb--------------------------------" rel="noopener ugc nofollow" target="_blank">learn.microsoft.com</a></p>
<p>For subscriptions, we would use an enum too. It would give us the possibility to compose permissions. For that reason, PermissionService is created. All the logic of permissions and subscriptions is located here.</p>
<p>So how we should use this service?<br />
When the access token is created, we put PermissionEnum in JWT payload. Then, this PermissionEnum would be available in each request.</p>
<p><a href="https://medium.com/@codewhale/do-not-use-roles-in-your-api-use-this-instead-c7b14deba1fb">Visit Now</a></p>