Sharepoint: COM exception thrown when navigating to the root of a new site collection - sharepoint

After a fresh install of WSS 3.0 and creation of a new web application and site collection, I receive the following error when I navigate to the newly create site:
[COMException (0x80070005): Access is denied.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +557
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_IsContainer() +42
System.DirectoryServices.ChildEnumerator..ctor(DirectoryEntry container) +36
System.DirectoryServices.DirectoryEntries.GetEnumerator() +36
Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.System.Web.IHttpModule.Init(HttpApplication app) +699
System.Web.HttpApplication.InitModulesCommon() +124
System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers) +1162
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context) +312
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context) +133
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +196

Seems to me like the application pool account does not have rights to do lookups in your Active Directory.. try running them using a domain account instead of network service.

What type of install do you choose for WSS (e.g. Standalone or Farm)?
As the installation is failing on DirectoryEntry.Bind it looks like an Active Directory issue. Is everything OK with your service accounts? Have you checked Event Viewer for any errors?

You should NEVER use Network Service as the app pool account, It is a user known only on themachine the site is ran on. Create an Active Directory user in your domain to run the app pool under. Then, in the Central Admin website under Operations -> Security Configuration -> Service Accounts set the new user for the app pool

Related

Get 401 Unauthorised calling WebApi from another WebAp on behalf of api (not user)

We have a number of ASPNET Core Web Apis in Azure that we call on behalf of a User. That user has normally signed into an ASPNET Web Site, also in Azure.
We are introducing an Audit Service. That feels like it should be called on behalf of the calling service rather that the authenticated user.
The Audit Service has an associated App Registration in Azure AD
The Audit Service has a scope called "access_as_application" although having seen documentation about a ".default" scope I wasn't sure that i needed a scope
The calling application (ASPNET Core Web Site) has been added in the "Authorized client applications" section against the previously mentioned scope
In the calling application I am getting an access token for the app rather than the user by using GetAccessTokenForAppAsync.
var accessToken = await this.tokenAcquisition.GetAccessTokenForAppAsync(this.auditApiScope);
System.Diagnostics.Debug.WriteLine($"access token-{accessToken}");
this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Currently I am running the calling application and the audit service on my local development machine.
When I make the call to the audit service I am getting a 401 Unauthorized
var response = await this.httpClient.PostAsync($"{this.auditApiBaseAddress}v1/entries", requestContent);
UPDATE
I have added the Azure Ad App Id of the calling application as a knownClientApplication on the Audit Service, via the App Manifest. That did not prevent the 401
"knownClientApplications": [
"7ac7f49d-e9fa-4e1b-95b2-03e0e1981f58"
],
UPDATE 2
I can see that the instance of the service running in Visual Studio is reporting a stack trace. It is referring to a IDW10201 issue.
System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.
at Microsoft.Identity.Web.MicrosoftIdentityWebApiAuthenticationBuilderExtensions.<>c__DisplayClass3_1.<<AddMicrosoftIdentityWebApiImplementation>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Identity.Web.MicrosoftIdentityWebApiAuthenticationBuilder.<>c__DisplayClass14_0.<<CallsWebApiImplementation>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Any thoughts why?
You should currently be performing server-to-server interaction, that is, no user involvement. So your server application needs to create an appRole, and then grant the app Role as an application permission to the client application.
First, you need to expose the api of the server application protected by Azure, which can be configured according to the following process:
Azure portal>App registrations>Expose an API>Add a scope>Add a client application
Then you need to create the appRole of the server application, and then grant that role as an application permission to the client application.
Next, go to client application>API permissions>Add a permission>My APIs>your api application.
Finally, you need to obtain an access token using the client credential flow where no user is logged in:
Parse the token:
Whilst I've marked Carl Zhao's contribution as the answer I found the screenshots a bit hard to follow so this is my attempt at making that a bit clearer.
In this scenario where we want authentication between Azure Ad registered application (client) and another Azure Ad registered application (Audit Service) scopes were not the solution. Rather than exposing a scope we needed to expose an appRole.
The steps required to expose and then request access to the app role were
App Registrations -> Audit Service -> Manage -> App roles -> Create app role
When creating the app role ensure the Allowed member type is "Applications"
Now go to App Registrations -> YourClientApplication -> Api permissions -> Add a permission
I expected the Audit Service to appear under "My APIs" in the "Request API permissions panel". I did not, the only way I could request permisison to the previously created AppRole was to enter the AppId of the Audit Service in the search box under "APIs my organization uses"
Once I was able to select the audit service I selected "Application permissions" rather than "Delegated permissions" and then I selected the specific role
Once the client application had been granted access we needed to write code get to an access token. Using Mictosoft.Identity.Web library
var accessToken = await this.tokenAcquisition.GetAccessTokenForAppAsync(this.auditApiScope);
System.Diagnostics.Debug.WriteLine($"access token-{accessToken}");
this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Note the call to GetAccessTokenForAppAsync not GetAccessTokenForUserAsync. GetAccessTokenForAppAsync still requires a scope however as already stated a custom scope is not needed. The scope is ".default" so the string passed to that call in our case was https://ourdomain/audit-service/.default" which is our App ID URI plus ".default"

Recycle App Pool Programmatically in IIS 10 / Windows Server 2019

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

Trying to get AAD and Azure SQL Authentication Working

I'm trying get integrated authentication working between my app, and azure SQL. The app is running on a VM that is joined to an Azure AD domain (Domain Services) on IIS.
I have followed this official MS document on setting up auth:
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-aad-authentication-configure (Note - we are not using managed instances for SQL).
1) The admin group has been added via the portal
2) The contained database user (also part of the admin group) has been created, per the doc.
3) The IIS application pool is running as the same user as well.
Attempts to connect to the site return this error:
[AdalException: Integrated Windows authentication supported only in federation flow.]
ADALNativeWrapper.ADALGetAccessToken(String username, IntPtr password, String stsURL, String servicePrincipalName, ValueType correlationId, String clientId, Boolean* fWindowsIntegrated, Int64& fileTime) +829
System.Data.SqlClient.<>c__DisplayClass2_0.<AcquireTokenAsync>b__0() +132
System.Threading.Tasks.Task`1.InnerInvoke() +121
System.Threading.Tasks.Task.Execute() +47
[AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +4323177
System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) +12865803
System.Threading.Tasks.Task`1.get_Result() +33
System.Data.SqlClient.<>c__DisplayClass134_1.<GetFedAuthToken>b__0() +39
System.Threading.Tasks.Task`1.InnerInvoke() +121
System.Threading.Tasks.Task.Execute() +47
[AggregateException: One or more errors occurred.]
Our web.config is using this as a connection string:
name="LocalSqlServer" connectionString="Server=tcp:XXXXX;Initial Catalog=XXXXX;Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication='Active Directory Integrated';" />
We're hoping to be able to remove any mention of plain-text passwords within our web.config, and azure authentication should be able to provide that.
Any help would be appreciated!
EDIT:
In an attempt to start fresh, I migrated the application to another fresh Azure VM. This time, the process initially lead to this error:
Unable to load adalsql.dll (Authentication=ActiveDirectoryPassword). Error code: 0x2.
After installing the .dll, it then leads me to the same error I posted above. Not sure if this initial error could shed some light on the underlying problem.
The error message is "Integrated Windows authentication supported only in federation flow"
From the portal, if you select "Azure Active Directory" and then select "Custom Domain names"
Do you have a single line on the list with "Primary" Selected?
If that is the case, you could try adding a new custom domain, mark that as federated and then use a user from that domain for the integrated authentication.
Recheck if the VM is on-premise or on-cloud because if your machine is on-prem and it is a joined AD, you should see it as a device in Azure Active Directory. Otherwise, when the machine is not integrated with ADFS, you will end up with the exception message "Integrated Windows authentication supported only in federation flow".
There are two possibles solutions:
- Integrate the machine into ADFS
- Use Active Directory Password with a valid account on Azure Active Directory.
In my scenario, I couldn't move the machine so I use an AD account.

Credentials manager for Azure Data Factory not working

Good day!
I am working on moving files via Azure Data Factory from on-prem file store and/or ftp site to Azure Blob storage using Copy Data activity. When setting security access, I am using credential manager. However, when clicking 'Set credential' a string 'Preparing...' shows for a split moment, and then nothing happens and box is left blank. What is exactly credentials manager? Is is a separate application, which needs to be installed or Windows credentials manager available via Administrative tools? I used IE for this. In Chrome it tries to install ClickOnce app, which fails to install with this error log (googling it reveals nothing). Does anyone know the solution?
IDENTITIES
Deployment Identity : CredentialsManager.application, Version=1.1.6273.1, Culture=neutral, PublicKeyToken=c3bce3770c238a49, processorArchitecture=msil
APPLICATION SUMMARY
* Online only application.
* Trust url parameter is set.
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of C:\Users\YToropov\Downloads\CredentialsManager.application resulted in exception. Following failure messages were detected:
+ Deployment and application do not have matching security zones.
COMPONENT STORE TRANSACTION FAILURE SUMMARY
No transaction error was detected.
WARNINGS
There were no warnings during this operation.
OPERATION PROGRESS STATUS
* [4/5/2017 5:50:08 AM] : Activation of C:\Users\YToropov\Downloads\CredentialsManager.application has started.
* [4/5/2017 5:50:08 AM] : Processing of deployment manifest has successfully completed.
* [4/5/2017 5:50:08 AM] : Installation of the application has started.
ERROR DETAILS
Following errors were detected during this operation.
* [4/5/2017 5:50:08 AM] System.Deployment.Application.InvalidDeploymentException (Zone)
- Deployment and application do not have matching security zones.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
COMPONENT STORE TRANSACTION DETAILS
No transaction information is available.
You may need to clean this folder and try again by using IE11.
C:\Users{account}\AppData\Local\Apps\2.0
if it still not work, you may need to reset the internet options.
Instead of trying to use the credentials manager, can I suggest you create your data factory in Visual Studio. Then simply deploy it to Azure with different sets of configuration files.
Check out this blog post on how.
https://www.purplefrogsystems.com/paul/2017/01/using-azure-data-factory-configuration-files/
This way credentials do not need to be copied into any portal blades and can be handled using other tools. Plus source controlled.
The JSON strings will also be masked if viewed via the Author and Deploy blade.
Plus any changes can be dealt with locally and your on prem linked service in ADF just redeployed.
Hope this helps.
The credential manager is a .NET ClickOnce application running on your OnPrem machine. When using the credential manager to set the username/password, it directly talks to the Gateway so there is no username/password data transfer over the wire. If you use "by web browser" option, the encrypted username/password will be transferred over the wire with a post request and then gets pushed to Gateway. In both options credentials are encrypted, but the Credential Manages saves the roundtrip through public network.
The reason why you get this error is because Chrome by default does not support the .NET ClickOnce application. It should work if you are using IE or Edge.
For this to work on Chrome, you can add an extention to enable ClickOnce application support in Chrome, like the below one
https://chrome.google.com/webstore/detail/meta4-clickonce-launcher/jkncabbipkgbconhaajbapbhokpbgkdc?hl=en
Solution: Clear the oneClick cache and try to install the application again. Here is the way to clear oneClick cache
From command line run: rundll32 dfshim CleanOnlineAppCache
If it doesn’t work, delete the real folder:
Windows Vista/7/8/10
C:\users[username]\AppData\Local\Apps\2.0\
Windows XP/2003
C:\Documents and Settings\username\LocalSettings\Apps\2.0\
for more information, you can look at this. it may be helpful.
http://codeketchup.blogspot.sg/2013/06/how-to-fix-deployment-and-application.html
======================================================
security zone

Can not access Azure SQL database after moving Azure API app to custom domain

I moved my API from free plan app service to a basic plan app service with custom domain and SSL certificate.
1) I see that my API app's status is "running", Authentication (AAD) is working properly
2) if I open it's api definition (i.e. */swagger/docs/v1) it IS working
3) If i try a request that does not try to access backend Azure sql db, then it is working correctly
4) If I use a request that call backend Azure SQL db (it worked before moving API to custom domain) it fails with this error:
{"The underlying provider failed on Open., StackTrace: at
System.Data.Entity.Core.EntityClient.EntityConnection.Open()\r\n at
System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean
shouldMonitorTransactions)\r\n at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at
System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass651.b__63()\r\n
at
System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func1
operation)\r\n at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String
commandText, String entitySetName, ExecutionOptions executionOptions,
Object[] parameters)\r\n at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String
commandText, ExecutionOptions executionOptions, Object[]
parameters)\r\n at
System.Data.Entity.Internal.InternalContext.<>c__DisplayClass141.b__13()\r\n
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()\r\n at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)\r\n
at
P..Repositories.DataAccessLayer.DbContexts.P..DbContext.GetP..Dtos()\r\n
at
P..Repositories.Repositories.P..Repository.P..Repository..ctor()\r\n
at P..API.Controllers.A..Controller.Get()"}]}
Only thing I've found so far suggests that my API can not access Azure SQL because of firewall rules, but that doesn't sound as an option, since I just assigned a custom domain to my app, I believe it is in the same "place" in Azure... and I did not manage so far to find any suggestions regarding Azure SQL db connections when migrating API to custom domains...
Any ideas?
It turns out, that by some strange reason, after moving to custom domain - publishing settings, AzureDatabase connection string had a non-existent (seams like "generated" name -> Api name with added postfix _db) database name. When I changed it to the real db name, everything started to work again...
P.S. I guess unchecking "use this connection string at runtime (update destination web.config)" would give the same result, since web.config holds the right connection string.

Resources