6

I've 3 models [User, Role, and UserRole]

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

Consider, the Role-based Authorization on controller using the [Authorize] attribute specifying 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 fine, What I need is,

Is there any way to assign my Role Collection to [Authorize] attribute? for example

I'll Fetch Assigned roles from Logged in User and store it in List. Is it possible to assign this List to [Authorize] attribute? something like as follows:

[Authorize(Roles = MyDynamicallyLoadedList)]
public class PageController : Controller
{
    // Controller code here
}
Unknown Coder
  • 1,510
  • 2
  • 28
  • 56

2 Answers2

1

Well, two problems.

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

Second, attributes parameter's values must be known at compile time : your list's content will only be known at runtime.

You'll get a message like :

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Solution would be to create a new Authorization attribute (inheriting from AuthorizeAttribute), and override AuthorizedCore

A example (that you could adapt to your problematic) can be found here

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
1

Yes.

  1. Override PostAuthenticateRequest in global.asax
  2. Load the roles from the db
  3. Create a new GenericPrincipal
  4. Assign the principal to 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;
    }
}
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • Can you suggest me some tutorials or blogs so I can go with step-by-step – Unknown Coder Sep 04 '12 at 12:09
  • Dude, Sorry, I'm pretty new to this, can you please provide me bit more detailed example? and How This can be applied to controller's [Authorize] attribute? – Unknown Coder Sep 04 '12 at 12:15
  • The above example loads all roles that the current user has. The roles specified in the attribute specifies the roles which are required for an action. They are two very different things. It's unclear what you really are looking for. – jgauffin Sep 04 '12 at 12:19