Ravi
Ravi

Reputation: 2558

Controlling access to methods

Is there a way to control access to methods to certain roles in .net. Like

class A
{
    //should only be called by Admins**
    public void Method1() { }

    //should only be called by Admins and PM's** 
    public void Method2() { }
}

I'm using windows authentication only for retrieving user names and nothing more.User roles are maintained in a different application. I think it's possible through attributes but I'm not really sure how

Upvotes: 7

Views: 412

Answers (3)

to StackOverflow
to StackOverflow

Reputation: 124696

You can do this as follows:

class A 
{     
    //should only be called by Admins**     
    [PrincipalPermission(SecurityAction.Demand, Role="Admin")] 
    public void Method1() 
    { 
    }      

    //should only be called by Admins and PM's**      
    [PrincipalPermission(SecurityAction.Demand, Role="Admin")] 
    [PrincipalPermission(SecurityAction.Demand, Role="PM")] 
    public void Method2() 
    { 
    } 
} 

To do this Thread.CurrentPrincipal must be set to a principal that has the required roles. For example, if you enable roleManager in an ASP.NET application, Thread.CurrentPrincipal will be set to a RolePrincipal with roles from your configured RoleProvider. See this MSDN article for more info.

Upvotes: 1

urz shah
urz shah

Reputation: 481

You can do it using custom validation.

1- Make a method in another public class which take login id as parameter and return roles in form of bits.

2- Call this method on the page_Load event of the required class and save returned bits in the view state.

3- Now validate required method on the basis of roles bits.

Upvotes: 0

Daniel Powell
Daniel Powell

Reputation: 8293

It it possible, I have used it on an web project that used asp.net and AzMan as the authentication.

Take a look at Code Access Security

From memory all of our methods looked something like

[Permission(SecurityAction.Demand, "Permission")]
public void Method1

It's been a while though so that might not be actually 100% correct.

I'd also highly suggest if you are going to put protection down to this level to look at a task orientated permission approach as this is much more flexible than role based permissions

Upvotes: 3

Related Questions