10

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")]
one noa
  • 345
  • 1
  • 3
  • 10
Benjamin Nguyen
  • 251
  • 3
  • 8

1 Answers1

10

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

Eric J.
  • 147,927
  • 63
  • 340
  • 553
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81
  • 1
    Are you saying that the PrinciplePermission attribute can be used outside of controllers/action methods, but the Authorize attribute cannot? – EF0 Aug 24 '16 at 15:47
  • Also, the PrinciplePermission attribute seems to give you the capability to do things like actively Deny a particular role as well (Maybe our method should accept access by all users with role 'Employee' except those who also have role 'Temporary'). – EF0 Aug 24 '16 at 15:48
  • @EFO yes, according to MSDN you can only use Authorize attribute on controllers or action methods. – emre nevayeshirazi Aug 24 '16 at 20:01