I am trying to implement a base-role authorization on my Web APIs but lately I realize that I cannot use this because I have a database where Roles are related to users (Many-Many) and Roles are related to Permissions (Many to Many) like Create , Update .... etc, So I am trying to find the best solution for user permissions and roles for authorizing access to actions in my APIs. Also, I don“t know if a better approach to this is making authorization just in the controllers for Front-end part and just generating an API key for avoiding third-parties programs getting access to my Web APIs.
Asked
Active
Viewed 143 times
1
1 Answers
0
If you are maintaining your own roles, privileges and user mapping inside your application, in that case you can't use the default role providers. For this type of scenarios you need to create your own role provider by extending System.Web.Security.RoleProvider
like following.
public class CustomRoleProvider : System.Web.Security.RoleProvider
{
List<string> userRoles;
public CustomRoleProvider()
{
//Populate the roles union privilege of logged in user inside userRoles
}
public override bool IsUserInRole(string username, string roleName)
{
//Mandatory to implement
}
public override string[] GetRolesForUser(string username)
{
//Mandatory to implement
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void CreateRole(string roleName)
{
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
return true;
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
Once you implement this, you need to register your RoleProvider in your configuration file like following.
<roleManager cacheRolesInCookie="false" defaultProvider="CustomRoleProvider" enabled="true">
<providers>
<clear/>
<add name="MyCustomRoleProvier" type="YourLibrary.CustomRoleProvider, YourLibraryName"/>
</providers>
</roleManager>
</system.web>
Now you can directly use the Authorization filter attribute in your API or Action like
[Authorize(Roles = "Admin")]
public string GetData()
{
}
You can check this answer also for more details. Custom Role Provider

PSK
- 17,547
- 5
- 32
- 43