Role-based authorization with a model list

I have 3 models [User, Role, UserRole]

  Use {ID [PK], Name, Email, Password, .....}
 Role {ID [PK], Name, Description, .......}
 UserRole {UserID [FK], RoleID [FK]}

Consider role-based authorization on a controller using the [Authorize] attribute, indicating that the user must be in the administrator role to access any controller action in the class

[Authorize(Roles = "Administrator")] public class PageController : Controller { // Controller code here } 

This is beautiful, I need

Is there a way to assign my role collection to the [Authorize] attribute? eg

I will select the assigned roles from the Recorded User and save it in the list. Can I assign this list to the [Authorize] attribute? something like the following:

 [Authorize(Roles = MyDynamicallyLoadedList)] public class PageController : Controller { // Controller code here } 
+6
source share
2 answers

Well, two problems.

First, you cannot use the List as a Attribute parameter. You can use an array instead. http://msdn.microsoft.com/fr-fr/library/ms177221%28v=vs.100%29.aspx

Secondly, attribute attribute values ​​must be known at compile time: the contents of the list will be known only at run time.

You will receive a message like:

The attribute argument must be a constant expression, typeof expression, or an array creation expression type attribute attribute

The solution would be to create a new authorization attribute (inheriting from AuthorizeAttribute ) and override AuthorizedCore

An example (which you can adapt to your problem) can be found here.

+1
source

Yes.

  • Override PostAuthenticateRequest in global.asax
  • Download roles from db
  • Create a New GenericPrincipal
  • Assign Thread.CurrentPrincipal and HttpContext.Current.User

Example:

 protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { string[] rolelist = GetRoleListForUserFromAPI(User.Identity.Name); HttpContext.Current.User = new GenericPrincipal(User.Identity, rolelist); Thread.CurrentPrincipal = HttpContext.Current.User; } } 
+1
source

Source: https://habr.com/ru/post/924524/


All Articles