Answered by:

WCF: PrincipalPermission (on methods) and Forms Authentication issue

Question

I'm developing mixed applications both asp.net and silverlight, everything works fine but to be able to use PrincipalPermissionAttribute on wcf service methods i need to force this line of code in Wcf service constructor:

System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;

Inspecting Global.asax 's PostAuthenticateRequest (executed before wcf service initialization) i can confirm that CurrentPrincipal has the right value, the system assigns to it the http current user correctly. When the execution flow reaches the wcf service
there is also a thread (managed thread id changes) switch and the currentPrincipal changes to a default not authenticated one (so i needed to add the previous line of code in the constructor to avoid it).

Reading Scott Hanselman's blogg ( http://www.hanselman.com/blog/AvoidUsingImpersonationInASPNET.aspx ) i see that Impersionation in asp.net is to be avoided if possible, so my question. Is what i used a trick and i'm infact using impersonation?
If so, what's the best way to deal with it?

Answers

I assume you’ve enabled AspNet compatibility for your service (so you can have a non null value for HttpContext.Current), but this
won’t have the runtime to set the CurrentPrincipal for the thread actually calling your service method, thus your principal permission demands will always fail.

The workaround you’ve implemented though is not 100% correct because there’s no guarantee that the runtime will create instances
of your service, and invoke your method, all in the same thread (in fact you can even be reusing an existing instance). A better approach (at least in your scenario) would be to set the principal via an ICallContextInitializier. Be careful though, as the suggested
approach will break if you set the PrincipalPermissionMode of your ServiceAuthorizationBehavior to anything but
None (which by the way is not even the default).

All replies

I assume you’ve enabled AspNet compatibility for your service (so you can have a non null value for HttpContext.Current), but this
won’t have the runtime to set the CurrentPrincipal for the thread actually calling your service method, thus your principal permission demands will always fail.

The workaround you’ve implemented though is not 100% correct because there’s no guarantee that the runtime will create instances
of your service, and invoke your method, all in the same thread (in fact you can even be reusing an existing instance). A better approach (at least in your scenario) would be to set the principal via an ICallContextInitializier. Be careful though, as the suggested
approach will break if you set the PrincipalPermissionMode of your ServiceAuthorizationBehavior to anything but
None (which by the way is not even the default).