AddObjectAuthorizationRules() Implementation Question

AddObjectAuthorizationRules() Implementation Question

Old forum URL: forums.lhotka.net/forums/t/12699.aspx


cslasoup posted on Tuesday, July 15, 2014

My team and I have been using CSLA.NET for a while now and recently we got the requirement to update how roles are processed.

In classic ASP.NET Membership you have a role.  For simplicity, let's just say it is the "ReadOnly" role.  To limit BusinessBase authorization for the that role, you would do something like the following:

protected static void AddObjectAuthorizationRules() {
    string[] read = new string[] { "ReadOnly" };
    Csla.Rules.BusinessRules.AddRule(typeof(LookUp), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.GetObject, read));
}

Our new role structure appends a user's Department to the role so now our roles look like "DeptName:RoleName".  We have the roles populating in our custom membership code/tables and we have a way to check the roles.  Here is what we will be implementing (code brevity to keep focus on the question's scope; new code is bolded):

protected static void AddObjectAuthorizationRules() {
    List<string> readUsers = new List<string>() { "ReadOnly"};
    Csla.Rules.BusinessRules.AddRule(typeof(LookUp), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.GetObject, ProcessAuthorizationRoles(readUsers)));
}

private static List<string> ProcessAuthorizationRoles(List<string> pDefinedRoles) {
    List<string> _userRoles = ((CustomIdentityClass)Csla.ApplicationContext.User.Identity).Roles;

    return _userRoles.FindAll(x => pDefinedRoles.Exists(y => x.Contains(string.Format(":{0}", y)))); }

How we can keep our code DRY within the CSLA framework without having to implement the same function (ProcessAuthorizationRoles) in each BusinessBase object?

Thanks in advance!

JonnyBee replied on Monday, July 21, 2014

Hi,

I am a bit puzzeled as to why you would need a "ProcessAuthorizationRoles" method in the first place. 

The IsInRole rule only needs get the pre-defined roles/permissions for having the permission. 

And AddObjectAuthorizationRules is only called once per type so you cannot have dynamic behavior (like editing permissions for this type in a database and expect these to take effect while the application is running).  

When the rule is executed it will ask the ApplicationContext.User (principal) if the user has any of the required permission (IsInRole). 

So:

Copyright (c) Marimer LLC