Try our conversational search powered by Generative AI!

Is it possible to do user impersonation outside of a scheduled job?


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?

Feb 13, 2018 12:20

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?

Feb 13, 2018 13:29

@erik: Yes, that throws the same error.

Feb 13, 2018 16:30

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?

Feb 13, 2018 16:35

In CMS, in the ProcessRequest method of a handler (implementing IRouteHandler and IHttpHandler) mapped like this:

RouteTable.Routes.Add(new Route
  new MyHandler()
Feb 13, 2018 16:40

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. embarassed

Feb 13, 2018 16:45

Hey Deane

This thread might be of some help:


Feb 13, 2018 16:46

That post showed me to how to do it another way, so thanks.

Feb 15, 2018 18:31
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.