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

Member since: 2008

I've used this line of code for years to impersonate a specific user inside of a scheduled job:

PrincipalInfo.CurrentPrincipal = ServiceLocator.Current.GetInstance<IUserImpersonation>().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?

#188156 Feb 13, 2018 12:20
  • Member since: 2012

    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?


    #188158 Feb 13, 2018 13:29
  • Member since: 2008

    @erik: Yes, that throws the same error.

    #188179 Feb 13, 2018 16:30
  • Member since: 2012

    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?

    #188181 Feb 13, 2018 16:35
  • Member since: 2008

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

    RouteTable.Routes.Add(new Route
      new MyHandler()

    #188182 Feb 13, 2018 16:40
  • Member since: 2012

    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

    #188184 Feb 13, 2018 16:45
  • Member since: 2008

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

    #188253 Feb 15, 2018 18:31