I've used this line of code for years to impersonate a specific user inside of a scheduled job:
PrincipalInfo.CurrentPrincipal = ServiceLocator.Current.GetInstance().CreatePrincipal(userName);
However, this doesn't seem to work outside of a scheduled job. When I attempt it, I get this:
ServiceLocationProvider must be set.
I'm attempting to implement a token auth scheme, where an anonymous request bearing a token can impersonate a specific user. Do I need to manually add the IUserImpersonation service to StructureMap?
The error message rather indicate that episerver haven't been properly initialized.
My first question is: do you get same error if you do this?
@erik: Yes, that throws the same error.
Then episerver haven't been initialized properly.
What context do you have? Are you trying this in the CMS site, the commerce site or in an application?
In CMS, in the ProcessRequest method of a handler (implementing IRouteHandler and IHttpHandler) mapped like this:
HttpHandlers are indeed a very special case as much of the episerver context isn't setup that early.
I'm afraid i can't help you further, i generally avoid placing code in http handlers.
This thread might be of some help: https://world.episerver.com/forum/developer-forum/-Episerver-75-CMS/Thread-Container/2017/9/scheduled-job-elevated-permissions-not-working/
That post showed me to how to do it another way, so thanks.