SPSecurity.RunWithElevatedPrivileges in Console Applications doesn´t work as expected

I made a discovery today about this little snippet of code:

SPSecurity.RunWithElevatedPrivileges(() => ….

As you would expect, when running this in SharePoint, you run a piece of code (the delegate) with the identity of the Application Pool account. An experiment of that is shown here:

StringBuilder sb = new StringBuilder();

sb.AppendFormat("{0}\n", SPContext.Current.Web.CurrentUser.LoginName);

SPSecurity.RunWithElevatedPrivileges(() =>
{
    using (SPSite site = new SPSite(siteUrl))
    using (SPWeb web = site.OpenWeb())
    {
        sb.AppendFormat("{0}\n", web.CurrentUser.LoginName);
        sb.AppendFormat("{0}\n", WindowsIdentity.GetCurrent().Name);
    }
});

Label.Text = sb.ToString();

image

 

I´m logged in as “Johan” on my SharePoint enviroment and it outputs that name before I start to run the same code with the identity of the app pool.

Nothing chocking…but if I run the same code (applied to console of course) in a console app, like this:

SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteUrl))
                using (SPWeb web = site.OpenWeb())
                {
                    Console.WriteLine(web.CurrentUser.LoginName);
                    Console.WriteLine(WindowsIdentity.GetCurrent().Name);
                }
            });

OK, nothing chocking here either, because I´m logged on to my VPC with the SharePoint system account (like most of us do).

image

But if I run that console app with “Run as…” and use my Johan identity, tada:

image

There is no impersonation done here, the code runs with your own credentials. This is good to know if you write programs that will need the credentials of the app pool, you have to use that account to execute the exe.

At least I didn´t know that.

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: