Benjamin Nguyen
Benjamin Nguyen

Reputation: 261

PrincipalPermission vs Authorize Attribute?

Can anybody explain to me the differences and use cases of these two attributes? I am quite confused since they behave similarly.

I know that the [Authorize] hooks into the ASP.NET application life cycle and run before the request reach to the Controller/Action. How about the PrincipalPermission?

[PrincipalPermission(SecurityAction.Demand, Role="Admin")]

And

[Authorize(Roles="Admin")]

Upvotes: 10

Views: 6142

Answers (1)

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

Authorize attribute is used to specifiy access restriction to a controller or action method. In other words, you can grant or deny users/roles access to visit individual pages or URLs within a site.

When you authenticate a user within an ASP.NET application, the authenticated user's identity will be automatically flowed throughout that user's request on the server.

You can use this identity information on business classes through PrincipalPermission attribute. With PrincipalPermission you can authorize a user's capabilities. For instance, you can prevent users from instantiating a class or accessing a method on your business classes.

This makes it easy to add clean security authorization rules to your business and data layers.

using System;
using System.Security.Permissions;

[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public class EmployeeManager
{
    [PrincipalPermission(SecurityAction.Demand, Role = "Manager")]
    public Employee LookupEmployee(int employeeID)
    {
       // todo
    }

    [PrincipalPermission(SecurityAction.Demand, Role = "HR")]
    public void AddEmployee(Employee e)
    {
       // todo
    }
}

For instance, using the PrincipalPermission attribute,

  • EmployeeManager class can only be instantiated by authorized users.
  • LookupEmployee method can only be accesssed by users with Manager role.

References

Adding Authorization Rules to Business and Data Layers

ASP.NET 2.0 Security Best Practices

Upvotes: 10

Related Questions