2

In C# 4.0+, is there a good way to restrict the allowable callers of a method, based on a method attribute?

I naively thought this was what CAS was all about -- and now the changes in .NET 4.0 appear to say the new CAS is only applied at the assembly level, and only on sandboxed apps ... which isn't what I'm after.

I'm imagining something like this:

[MyDangerousPermission]
public void DoSomethingDangerous()
{
    . . .
}

and in another class or assembly:

[MyDangerousDemand]
public void AllowedCaller()
{
    DoSomethingDangerous();
}

and that without [MyDangerousDemand] somewhere in the call stack, any calls to DoSomethingDangerous() would fail (throw a SecurityException, for example).

Not possible?

(my main application is in a web app, in case it matters).

RickNZ
  • 18,448
  • 3
  • 51
  • 66
  • CAS was never meant to secure a web app, it was designed to protect against code you don't trust. Allowing users to upload code to a web server is ... unwise. But is possible, you'd of course mistrust the entire assembly they upload, not just one method. If you don't trust your own code then you have a bigger problem. High odds that you are simply looking in the wrong corner. – Hans Passant May 09 '14 at 10:47
  • My app doesn't involve any uploaded code; that's not the scenario I'm trying to protect against. – RickNZ May 09 '14 at 19:50

1 Answers1

0

We still use CAS as you specicy and have not experience any trouble. Look at the PrincipalPermissionAttribute.

However, if it's a web application you should probably use one of the attributes created by the framework you are using. For ASP.NET MVC it's called AuthorizeAttribute. i.e. do the authorization in the top layer and not in the business layer.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • `AuthorizeAttribute` won't work for this application; the system only has anonymous users -- no one is "authorized." – RickNZ May 14 '14 at 07:13
  • If no one is authorized, how do you expect CAS to work? – jgauffin May 14 '14 at 07:16
  • When a "Permission" attribute is present, I'd like it to walk up the call stack and look to see if a matching "Demand" attribute is present on one of the callers. The idea is to be able to limit access to sensitive code to a small number of callers, mainly for the purpose of catching programming or policy errors. – RickNZ May 14 '14 at 12:12