Here is my code snippet:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSolution newSolution = SPFarm.Local.Solutions.Add(#fullPath);
});
The stacktrace and innerexception give no further clues. The Exception.Source says Microsoft.SharePoint.
SPFarm.Local.CurrentUserIsAdministrator() returns TRUE for the userid.
The userid is in the Farm Administrators group.
Any ideas?
EDIT
I have changed my code to the following and still get the Access Denied error:
private void AddSolution()
{
SPSolution newSolution = SPFarm.Local.Solutions.Add(#fullPath);
}
SPSecurity.CodeToRunElevated elevatedAddSolution = new SPSecurity.CodeToRunElevated(AddSolution);
SPSecurity.RunWithElevatedPrivileges(elevatedAddSolution);
Your main problem might just be that you are not DBO of a sharepoint database (_Config if I'm not wrong). Adding a solution to a farm is something that require more rights than just access to the farm.
Be sure that the user running this is Farm Administrator and DBO of the proper database.
If you still have problem... try running
stsadm -o addsolution -filename
"myWsp.wsp"
If you have the proper right, it will give you the proper error.
Have you tried declaring the delegate outside of the call to RunWithElevatedPriviliges?
Edit: Ignore below as you appear to have checked permissions.
RunWithElevatedPriviliges will use the identity of the application pool which SP is running under. Have you ensured this account has sufficient privileges in your environment?
I do believe that the issue you are having is due to the fact that you are using the static member to access the SPFarm object. I think that it is similar to running the SPcontext static class which will still run under the security context of the logged on user and not under the elevated privledges context (which is the local application pool identity).
Try this instead inside your delegate:
SPFarm spFarm = SPWebService.AdministrationService.Farm;
SPSolution newSolution = spFarm.Solutions.Add(#fullPath);
EDIT:
Since the above didn't help then your issue probably has to do with database permissions to the config database. The RunWithElevatedPriviliges will run under the application pool's identity that the code is running under. Adding a solution to your farm affects the configuration database so your application pool identity will need access to the config database. As a test try adding the app pool identity to the config db and give it dbo permissions. If that fixes the issue then you will need to find the minimum amount of permissions that each of your app pool accounts will need to add solutions (do not leave as dbo)
Related
I'm trying to create a function that will allow a user to reset/recycle an application pool on demand in order to reload updated IIS site settings, however I'm running into a permissions issue anytime I try to use a ServerManager function.
ServerManager serverManager = new ServerManager();
ApplicationPool appPool = serverManager.ApplicationPools[site_list.SelectedValue];
if (appPool != null) {
if (appPool.State == ObjectState.Stopped) {
appPool.Start();
} else {
appPool.Recycle();
}
}
Any time I run the code, I get the following error:
Filename: redirection.config Error: Cannot read configuration file due
to insufficient permissions
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Filename:
redirection.config Error: Cannot read configuration file due to
insufficient permissions
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
I've tried granting read permissions to the redirection.config file to any/all of the following users with no change:
ASPNET
NETWORK SERVICE
IUSR
IIS_IUSRS
Anyone happen to have any insight on how to recycle an AppPool through code?
I can get it work when I set application pool identity to LocalSystem and anonymous authentication->Edit->Use application pool identity.
I think if you don't want to use LocalSystem, then you have to grant special permission for C:\Windows\System32\inetsrv\config folder and your application root folder. It will also reduce the security of your computer.
Microsoft Process monitor could help you grant NTFS permission. You could add a filter for "process name=w3wp.exe" and "result=access denied".
https://learn.microsoft.com/en-us/sysinternals/downloads/procmon
I'm quite sure, the answer must be somewhere but I googled my ass off:
I know that "elevated privilegues" runs with the appPool-Account. But what account is used for
web.Site.SystemAccount in SharePoint? Is it the farm admin?
MSDN documentation says that
SPSite.SystemAccount Gets the system account of the site collection
In addition, Reflector says that SystemAccount user ID is 1073741823 that corresponds to SHAREPOINT\system:
<m:properties>
<d:Id m:type="Edm.Int32">1073741823</d:Id>
<d:IsHiddenInUI m:type="Edm.Boolean">false</d:IsHiddenInUI>
<d:LoginName>SHAREPOINT\system</d:LoginName>
<d:Title>System Account</d:Title>
<d:PrincipalType m:type="Edm.Int32">1</d:PrincipalType>
<d:Email></d:Email>
<d:IsShareByEmailGuestUser m:type="Edm.Boolean">false</d:IsShareByEmailGuestUser>
<d:IsSiteAdmin m:type="Edm.Boolean">false</d:IsSiteAdmin>
<d:UserId m:type="SP.UserIdInfo">
<d:NameId>S-1-0-0</d:NameId>
<d:NameIdIssuer>urn:office:idp:activedirectory</d:NameIdIssuer>
</d:UserId>
</m:properties>
this account is the primary administrator of Site collection which you can configure from Central admin.
I am afraid the RUNwithElevatedPrivileges is run by System account not app pool account. Because normally we use a separate app pool account than site collection administrator. If you debug the code and get SPContext with in RWEP... you will get System account syntax.
below article is explaining .
[http://www.mssharepointtips.com/tip.asp?id=1022][1]
I have an ASP.NET Web API service that runs on a web server with Windows Authentication enabled.
I have a client site built on MVC4 that runs in a different site on the same web server that uses the HttpClient to pull data from the service. This client site runs with identity impersonation enabled and also uses windows authentication.
The web server is Windows Server 2008 R2 with IIS 7.5.
The challenge I am having is getting the HttpClient to pass the current windows user as part of its authentication process. I have configured the HttpClient in this manner:
var clientHandler = new HttpClientHandler();
clientHandler.UseDefaultCredentials = true;
clientHandler.PreAuthenticate = true;
clientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
var httpClient = new HttpClient(clientHandler);
My understanding is that running the site with identity impersonation enabled and then building the client in this manner should result in the client authenticating to the service using the impersonated identity of the currently logged in user.
This is not happening. In fact, the client doesn't seem to be authenticating at all.
The service is configured to use windows authentication and this seems to work perfectly. I can go to http://server/api/shippers in my web browser and be prompted for windows authentication, once entered I receive the data requested.
In the IIS logs I see the API requests being received with no authentication and receiving a 401 challenge response.
Documentation on this one seems to be sparse.
I need some insight into what could be wrong or another way to use windows authentication with this application.
Thank You,
Craig
I have investigated the source code of HttpClientHandler (the latest version I was able to get my hands on) and this is what can be found in SendAsync method:
// BeginGetResponse/BeginGetRequestStream have a lot of setup work to do before becoming async
// (proxy, dns, connection pooling, etc). Run these on a separate thread.
// Do not provide a cancellation token; if this helper task could be canceled before starting then
// nobody would complete the tcs.
Task.Factory.StartNew(startRequest, state);
Now if you check within your code the value of SecurityContext.IsWindowsIdentityFlowSuppressed() you will most probably get true. In result the StartRequest method is executed in new thread with the credentials of the asp.net process (not the credentials of the impersonated user).
There are two possible ways out of this. If you have access to yours server aspnet_config.config, you should set following settings (setting those in web.config seems to have no effect):
<legacyImpersonationPolicy enabled="false"/>
<alwaysFlowImpersonationPolicy enabled="true"/>
If you can't change the aspnet_config.config you will have to create your own HttpClientHandler to support this scenario.
UPDATE REGARDING THE USAGE OF FQDN
The issue you have hit here is a feature in Windows that is designed to protect against "reflection attacks". To work around this you need to whitelist the domain you are trying to access on the machine that is trying to access the server. Follow below steps:
Go to Start --> Run --> regedit
Locate HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0 registry key.
Right-click on it, choose New and then Multi-String Value.
Type BackConnectionHostNames (ENTER).
Right-click just created value and choose Modify.
Put the host name(s) for the site(s) that are on the local computer in the value box and click OK (each host name/FQDN needs to be on it's own line, no wildcards, the name must be exact match).
Save everything and restart the machine
You can read full KB article regarding the issue here.
I was also having this same problem. Thanks to the research done by #tpeczek, I developed the following solution: instead of using the HttpClient (which creates threads and sends requests async,) I used the WebClient class which issues requests on the same thread. Doing so enables me to pass on the user's identity to WebAPI from another ASP.NET application.
The obvious downside is that this will not work async.
var wi = (WindowsIdentity)HttpContext.User.Identity;
var wic = wi.Impersonate();
try
{
var data = JsonConvert.SerializeObject(new
{
Property1 = 1,
Property2 = "blah"
});
using (var client = new WebClient { UseDefaultCredentials = true })
{
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
client.UploadData("http://url/api/controller", "POST", Encoding.UTF8.GetBytes(data));
}
}
catch (Exception exc)
{
// handle exception
}
finally
{
wic.Undo();
}
Note: Requires NuGet package: Newtonsoft.Json, which is the same JSON serializer WebAPI uses.
The reason why this is not working is because you need double hop authentication.
The first hop is the web server, getting impersonation with Windows authentication to work there is no problem. But when using HttpClient or WebClient to authenticate you to another server, the web server needs to run on an account that has permission to do the necessary delegation.
See the following for more details:
http://blogs.technet.com/b/askds/archive/2008/06/13/understanding-kerberos-double-hop.aspx
Fix using the "setspn" command:
http://www.phishthis.com/2009/10/24/how-to-configure-ad-sql-and-iis-for-two-hop-kerberos-authentication-2/
(You will need sufficient access rights to perform these operations.)
Just consider what would happen if any server was allowed to forward your credentials as it pleases... To avoid this security issue, the domain controller needs to know which accounts are allowed to perform the delegation.
To impersonate the original (authenticated) user, use the following configuration in the Web.config file:
<authentication mode="Windows" />
<identity impersonate="true" />
With this configuration, ASP.NET always impersonates the authenticated user, and all resource access is performed using the authenticated user's security context.
I have a custom form that lists the site groups and the users in each group.
the form has twi drop down lists: one to display the site's group and the other to display the users in that group.
when I log to the form with the administrator user it works fine.
But if I log in with a user with manage hierarchy permission level, it omly displays the info of the domain groups and if I try to access a sharepoint group I get an access denied error.
I use run with elevated permissions in my code
I really don't know what to do in this
thanks.
Two common mistakes when using RunWithElevatedPrivileges is:
Using the SPContext.Current.Web (or Site etc) won't change the identity of the web object, it is already in memory.
Declaring the SPWeb outside the delegate, with similar results of mistake 1
That said, try something like:
Guid siteId = SPContext.Current.Site.Id;
SPSecurity.RunWithElevatedPrivileges(() =>
using (SPSite elevatedSite = new SPSite(siteId))
using (SPWeb elevatedWeb = elevatedSite.RootWeb)
{
//impl
});
I'm trying to run a console application that uses the SharePoint Object Model.
I'm getting the error Cannot open database "dbname" requested by the login. The login failed. Login failed for user 'DOMAIN\userid'.
Some place I have read that the user must have permission to the Content DB.
I can not find an article that explains what permissions to setup. I need this as ammunition to go to my Sys Admin guy to get the permission setup.
Where is there an article that explains that? I have searched google but with no luck.
RunWithElevatedPrivileges doesn't help because it just changes the thread user to the process identity - in a console application, this has no effect because they're the same. The "elevation" in an impersonated web context works because the process identity is the application pool account, which has db_owner on its content database.
If I ask that the account I'm using be given Full Control, under the Policies for Web Application, should that work?
Not according to Ishai Sagi: Object model code and stsadm fail with "Access Denied". In short, it seems db_owner permissions on the content database are required for a user to run object model code (including STSADM) without a web context.
Are you running the console application on the server itself? I assume so.
In this case it is likely to be a permissions issue with the account you are using (RDP?) on the server. The database error side of things can be misleading as you will need to be permissioned within SharePoint itself, which will then give permissions to the database.
I would get your sys admins to create a service account for you to use that can be granted the correct rights. (site collection administrator is often needed, but it depends on the code inside the console app. most do assume site collection admin rights though). you may get more mileage from looking at the application instructions (or if it is your own code just go for site collection admin)
Running a console app is a bit of a major though, so you may have better luck if you give the sysadmins the application to run and instructions... though I doubt you are running this on the prod box.
your user propably don't have permissions to access those lists or webs. You can run your code with elevated privilegies, but it can sometimes give you unexpected results.
Example of how elevated privilegies is used can be found here
Or you can set user unser who's account console app runs as site collection administrator.
Your code updated to run with elevated privilegies can look like this:
private static void DisplayAllLists(string site, string webToOpen)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using ( SPSite siteCollection = new SPSite(site) )
{
try
{
using (SPWeb web = siteCollection.OpenWeb(webToOpen))
{
SPListCollection lists = web.Lists;
foreach (SPList list in lists)
{
Console.WriteLine(string.Format("List Title: {0}", list.Title));
}
}
}
}
finally
{
siteCollection.RootWeb.Dispose();
Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: "+ex.Message);
}
}
Note: This code was written from top of my head, so maybe something is missing..you will have to try it