Question

We want piece of code which we can paste in the code behind and get the username under which code runs for:- (usually .NET code runs under account of application pool)

  1. Timer job.

  2. Event receiver.

  3. Webpart.

  4. Layouts application page.

  5. User Control

  6. JSOM

Then, we want to use RWEP and again check which username code is running under.

What snippet do we use?

UPDATE

I do not want code that gives me the username of logged in user. I want the code that will give me the accountname under which the code will run.

UPDATE

For an application page:

  SPUser user1 = SPContext.Current.Web.CurrentUser;
        string userName1 = user1.Name;

Gives value as: Logged in username.

 SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(idd))
            {
                using (SPWeb rootWeb = site.OpenWeb())
                {
                    SPUser user2 = SPContext.Current.Web.CurrentUser;
                    string userName2 = user2.Name;
                }

            }
        });

Gives value as: Logged in user name.

 var User = System.Security.Principal.WindowsIdentity.GetCurrent().User;
        var UserName = User.Translate(typeof(System.Security.Principal.NTAccount)).Value;

Gives value as: NT AUTHORITY\IUSR

  SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite(idd))
            {
                using (SPWeb rootWeb = site.OpenWeb())
                {
                    var User12 = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                    var UserName12 = User12.Translate(typeof(System.Security.Principal.NTAccount)).Value;                        
                }

            }
        });

Gives value as: servername\spadminaccountname

UPDATE

(In our case, the site coll. admin username is same as the web application apppool username, so which account is it really?)

1) Can we conclude that the credentials under which code runs is the 'NT AUTHORITY\IUSR' and if we use RWEP then the user is 'webapp/sitecol admin user acount'? For example suppose we are accessing a file on the server then, the above 2 accounts will be used to access the file and not the account of logged in user.

2) Which account is used when accessing SharePoint resources? Is it one of the 2 above or the logged in users credentials?

Was it helpful?

Solution

NotVonKaiser in this case is correct:

1 runs under farm account and all others are under logged in user account!

The logged in user account will call the nt/authenticated account on the server that he/she has authentication on the server todo what he is requesting todo! if that makes sense ;)

think of nt/authenticated as if you are physically logging on to the server todo a specific task like you would on your desktop pc when you power up the machine to logonto windows!

so to make this clear:

2-6 run under current logged in user account that has nt authentication(allowed to access whatever resource is needed)

now saying this, there is another factor involved and that has todo with your web.config and cas policy (code access security policy), depending on what you set (full, partial, low) will determin the access you would have to the resources under the current logged in account!

In terms of deployment, the only differences between the full-trust execution model and the bin/CAS execution model are the location where you deploy your assemblies and the code access security policies associated with that location. In both cases, any non-compiled items, such as ASP.NET markup files, XML files, or resource files, are typically deployed to the SharePoint root on each Web front-end server. If you want to deploy a farm solution using either of the farm solution execution models, you must have access to the server file system and be a member of the Farm Administrators security group.

http://msdn.microsoft.com/en-us/library/ff798412.aspx

most code is executed under the current logged in user account.... unless you user reunwithelevatedprivlages than that is somthing else!

now to the question which i belive is somthing more complex and deeper i belive what your looking for it has todo with the worker process!

so you login to the machine -> goto sharepoint site that authenticates your account (nt authentication) -> than you perform a job that is run under the worker process w3wp.exe and i think it is this that your refering to?

A worker process is user-mode code whose role is to process requests, such as processing requests to return a static page, invoking an ISAPI extension or filter, or running a Common Gateway Interface (CGI) handler.

In both application isolation modes, the worker process is controlled by the WWW service. However, in worker process isolation mode, a worker process runs as an executable file named W3wp.exe, and in IIS 5.0 isolation mode, a worker process is hosted by Inetinfo.exe. Figure 2.2, which depicts the architecture for IIS 5.0 isolation mode, uses a dashed line to suggest the relationship between the worker process and the WWW service.

Worker processes use HTTP.sys to receive requests and to send responses by using HTTP. Worker processes also run application code, such as ASP.NET applications and XML Web services. You can configure IIS to run multiple worker processes that serve different application pools concurrently. This design separates applications by process boundaries and helps achieve maximum Web server reliability.

By default, worker processes in worker process isolation mode run under the Network Service account, which has the strongest security (least access) compatible with the functionality that is required.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/29f53968-0115-451f-b26d-5ad58d87b5d1.mspx?mfr=true

so the iis worker process would be the one executing the code at the bottom but to do this in the first place you need to be nt authenticated regarless!

the following link shows a better understanding!

http://msdn.microsoft.com/en-us/library/ff798428.aspx

EDIT

1) Can we conclude that the credentials under which code runs is the 'NT AUTHORITY\IUSR' and if we use RWEP then the user is 'webapp/sitecol admin user acount'? For example suppose we are accessing a file on the server then, the above 2 accounts will be used to access the file and not the account of logged in user.

ok i think your getting confused?

there are two stages to this.... the user logs into the machine yes? that user has access and is part of 'NT AUTHORITY\IUSR' so he is able to access specific resources that require you to be 'NT AUTHORITY\IUSR' within sharepoint..... now running code on the backend of the server will be within w3wp.exe (like .cs code (within assembly))... this is run under the application pool account.. but this wont run unless the logged in user is part of 'NT AUTHORITY\IUSR'. Its not one or the other, more like both at the same time being used.

You know the logged in account that your using obviouslt ;) but to know the w3wp.exe you need to goto the server and goto tast manager, look at processes and find w3wp.exe... you should see the column next to it with the user name which would be the web application pool account.

2) Which account is used when accessing SharePoint resources? Is it one of the 2 above or the logged in users credentials?

sharepoint resources are accessed by the logged in user. same as above.

OTHER TIPS

1 should always run under the farm account.

For 2, 3, 4, and 5, you should be able to ferret this information out by using this code:

SPUser user = SPContext.Current.Web.CurrentUser;
string userName = user.Name; //you can also call user.Email here

Note that this will not work correctly if you have a 'RunWithElevatedPrivileges' delegate block. Rather, if you call it within the delegate block, you'll just get the name of the account that is running the code. If you need to supply a username in that case, call the 'SPContext' object before or after you run the delegate block. You won't be able to pass the object into the delegate block directly but you should be able to extract what you need into strings or what have you and send them in.

For CSOM, assuming you're using JavaScript, this code block comes from this MS page:

function getUserProperties() {

// Replace the placeholder value with the target user's credentials.
var targetUser = "domainName\\userName";

// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);

// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
personProperties = peopleManager.getPropertiesFor(targetUser);

// Load the PersonProperties object and send the request.
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}

// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {

// Get a property directly from the PersonProperties object.
var messageText = " \"DisplayName\" property is "
    + personProperties.get_displayName();

// Get a property from the UserProfileProperties property.
messageText += "<br />\"Department\" property is "
    + personProperties.get_userProfileProperties()['Department'];
$get("results").innerHTML = messageText;
}

// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$get("results").innerHTML = "Error: " + args.get_message();
}

You'll have to have SP.js preloaded before this script runs, either by sticking it into the master page or by adding a 'SharePoint:ScriptLink' block for it in your markup.

Basically, what you have to do is this:

  1. Call the client context.
  2. Tell the client context what you want to retrieve from it.
  3. Make an asynchronous call to the web service to get that information.
  4. Set up callback methods to handle the data if the async call is successful or not.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top