0

I have an object with several methods. Some of which are decorated with a [AuthenticationRequired] attribute. When, and how, should I be checking whether the callee is authenticated?

This is just a simple null check, but I don't know how to hook it to the actual method calls. I'm kind of lost here.

Do I:

  1. Use a StackFrame, determine the top-level method called on this class, and then figure out possible authentication issues?
  2. Include this check in every single method that has the attribute? What's the attribute good for, then?
  3. Somehow hook to all method calls on my class, figuring out whether they have the attribute?

The class structure is roughly:

public class Stuff
{
     public void ImFine()
     {
         CommonMethod("fine");
     }

     public void ImGood()
     {
         CommonMethod("good");
     }

     [AuthenticationRequired]
     public void ImTerrible()
     {
         CommonMethod("terrible", true); // not an optional parameter.
     }

     [AuthenticationRequired]
     public void ImDeceased()
     {
         CommonMethod("dead");
     }

     protected void CommonMethod(string state)
     {
         Console.WriteLine(string.Format("I feel {0}", state));
     }

     protected void CommonMethod(string state, bool pet)
     {
         if (pet)
         {
             Console.WriteLine(string.Format("My pet feels {0}", state));
         }
         else
         {
             Console.WriteLine(string.Format("I feel {0}", state));
         }
     }
}

Assume CommonMethod is barely more complex and one can't invoke the other (in order to have one method shared by every callee).

Community
  • 1
  • 1
bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • `What's the attribute good for, then?` Not much I can think of. You'd need an AOP style tool so that the method IL gets rewritten to inject the authorization checking code. PostSharp is popular. – Hans Passant Jan 15 '12 at 15:27

1 Answers1

1

Have you thought about aspect oriented programming? You may take a look at some of implementations, ie: PostSharp or Castle.

empi
  • 15,755
  • 8
  • 62
  • 78