Security.PrincipalPermission.Demand()

  • Thread starter Thread starter Jeroen
  • Start date Start date
J

Jeroen

Hi,

Normally my programming style is as follows:

/****************/
if ( SomeObject.CanYouDoThis() == true)
SomeObject.DoStuff();
else
MessageBox.Show("Nope, sowwy...");
/****************/

Meaning, most usually I don't just call "DoStuff()" and show the 'nope
sowwy' message if I caught an exception.

Now, the question is: can someone explain why the
PrincipalPermission's Demand method seems to work like this? MS
recommends to try the Demand() method before you do something secure,
and catch any exception to handle non-authenticated users. This seems
a bit like misusing exceptions?

Thanks.

-Jeroen
 
MsgBox is fine at the UI, and indeed the UI would be correct to check
whether something should work before attempting it (by calling
IsInRole) - however, when you're a few layers down (i.e. not touching
the UI), the best way to indicate "nope, sowwy" is to throw an
exception. To me, this is entirely reasonable behavior if the caller
has failed to enforce the pre-requisites for a method (i.e. that the
user is in a given role), and is *correctly* using exceptions. Return
codes are generally simply not a good way of indicating success
[although it is fine for the bool TrySomething(...) signatures].

In fact, the runtime takes it a level further; you can mark a method
with the [PrincipalPermission(Demand...blah)] attribute and it will
enforce it at the point the method is invoked - again, throwing an
exception as a perfectly well-defined "as if!" response.

Marc
 
Back
Top