I have a controller that authorizes logged in users based on roles.
now we have a generic website that allows users from different companies to login, how do I dynamically restrict the controllers based on roles.
Here is my code
[Authorize(Roles = "CompanyA")] ///how can I dyanmicaly set the Roles e.g CompanyB, CompanyC etc
public ActionResult Index()
{
your code
}
UPDATE BASED ON @MISHA130 Advise
Problem now is how to I get the authenticated user and which roles he/she has ? thanks
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
// Go to the database, check your user role compare if the user can do it.
// do all your logic here
var xx = HttpContext.User.Identity.Name;
var a = User.Identity.GetUserId();
var x = HttpContext.Current.User.Identity.Name;
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // will give the user's userId
var userNames = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
isAuthorized = await _userManager.IsInRoleAsync(userName, "RSA Test");
if (!isAuthorized)
{
context.Result = new ForbidResult();
}
}