RavenDB doesnt work with FQDN - ravendb

We are using RavenDB installed as windows service. All of the apps connect to Raven using the IP .
I was trying to use the FQDN for the machine instead of using IP in the app configurations, but when I use the FQDN I get following error. Not able to nail down whats going wrong.
Have read articles that suggests change of web.config for the authentication.
If authentication or config is issue how does it work with IP and fail with FQDN ?
any help/ pointer appreciated
The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()
at Raven.Client.Connection.HttpJsonRequest.ReadJsonInternal(Func`1 getResponse)
at Raven.Client.Connection.HttpJsonRequest.ReadResponseJson()
at Raven.Client.Connection.ServerClient.DirectPut(RavenJObject metadata, String key, Etag etag, RavenJObject document, OperationMetadata operationMetadata)
at Raven.Client.Connection.ServerClient.<>c__DisplayClass13.<Put>b__12(OperationMetadata u)
at Raven.Client.Connection.ReplicationInformer.TryOperation[T](Func`2 operation, OperationMetadata operationMetadata, OperationMetadata primaryOperationMetadata, Boolean avoidThrowing, T& result, Boolean& wasTimeout)
at Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication[T](String method, String primaryUrl, OperationCredentials primaryCredentials, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation)
at Raven.Client.Connection.ServerClient.ExecuteWithReplication[T](String method, Func`2 operation)
at Raven.Client.Document.HiLoKeyGenerator.PutDocument(IDatabaseCommands databaseCommands, JsonDocument document)
at Raven.Client.Document.HiLoKeyGenerator.GetNextRange(IDatabaseCommands databaseCommands)
at Raven.Client.Document.HiLoKeyGenerator.NextId(IDatabaseCommands commands)
at Raven.Client.Document.HiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention convention, Object entity)
at Raven.Client.Document.MultiTypeHiLoKeyGenerator.GenerateDocumentKey(IDatabaseCommands databaseCommands, DocumentConvention conventions, Object entity)
at Raven.Client.Document.DocumentStore.<>c__DisplayClass4.<Initialize>b__2(String dbName, IDatabaseCommands databaseCommands, Object entity)
at Raven.Client.Document.DocumentConvention.GenerateDocumentKey(String dbName, IDatabaseCommands databaseCommands, Object entity)
at Raven.Client.Document.GenerateEntityIdOnTheClient.GenerateDocumentKeyForStorage(Object entity)
at Raven.Client.Document.InMemoryDocumentSessionOperations.StoreInternal(Object entity, Etag etag, String id, Boolean forceConcurrencyCheck)
at Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity)
at Insight.RavenDB.RavenPersistenceEngine.Persist(IPersistableObject pe)
The target principal name is incorrect
at System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatus& statusCode)
at System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob)
at System.Net.NegotiateClient.DoAuthenticate(String challenge, WebRequest webRequest, ICredentials credentials, Boolean preAuthenticate)
at System.Net.NegotiateClient.Authenticate(String challenge, WebRequest webRequest, ICredentials credentials)
at System.Net.AuthenticationManager.Authenticate(String challenge, WebRequest request, ICredentials credentials)
at System.Net.AuthenticationState.AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo)
at System.Net.HttpWebRequest.CheckResubmitForAuth()
at System.Net.HttpWebRequest.CheckResubmit(Exception& e, Boolean& disableUpload)

The reason is probably this issue:
http://ayende.com/blog/16385/more-auth-issues-0xc000006d-on-windows-2008-r2

Related

Active Directory Interactive authentication in ASP.NET Core Razor Pages Web App not working when deployed to Azure App Service

I have a web-app that is used to interact with an azure SQL database. It is working as intended, however when I change from using an SQL user/pass in the connection string to using Active Directory Interactive, I get an error when the web-app should be prompting to log in.
Please note this only occurs when the app is published as an Azure App Service, locally it works as intended.
I'm inexperienced so I'm having a hard time making sense of the error.
Below is my connection string.
"Connection1": "Server=xxx.database.windows.net; Initial Catalog=xxx; Authentication=Active Directory Interactive;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
And this is the error I receive when the user uses the connection string when loading a new page in development mode.
I'm honestly pretty overwhelmed with this. It seems like some sort of machine configuration issue and I don't know where to start.
Any advice appreciated! Stack below:
System.AggregateException: One or more errors occurred. (One or more errors occurred. (An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.))
---> System.AggregateException: One or more errors occurred. (An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.)
---> MSAL.NetCore.4.39.0.0.MsalClientException:
ErrorCode: http_listener_error
Microsoft.Identity.Client.MsalClientException: An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.
---> System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.InterceptAuthorizationUriAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenInteractiveDeviceFlowAsync(IPublicClientApplication app, String[] scopes, Guid connectionId, String userId, SqlAuthenticationMethod authenticationMethod)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<>c__DisplayClass17_0.<<AcquireTokenAsync>b__0>d.MoveNext()
Inner Exception: System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass146_1.<GetFedAuthToken>b__1()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__271_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of inner exception stack trace ---
at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at xxx.Pages.xxx.IndexModel.OnGetAsync() in C:\Users\xxx\source\repos\xxx\xxx\Pages\xxx\Index.cshtml.cs:line 37
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
MSAL.NetCore.4.39.0.0.MsalClientException:
ErrorCode: http_listener_error
Microsoft.Identity.Client.MsalClientException: An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.
---> System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.InterceptAuthorizationUriAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenInteractiveDeviceFlowAsync(IPublicClientApplication app, String[] scopes, Guid connectionId, String userId, SqlAuthenticationMethod authenticationMethod)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<>c__DisplayClass17_0.<<AcquireTokenAsync>b__0>d.MoveNext()
Inner Exception: System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
I ended up getting things to work. In your appsettings for your deployed connection string set it to
Authentication=Active Directory Managed Identity;User Id='your azure object/principal id'
make sure the userid is the azure object/principal id and not the azure client id
I made a helper so I don't have to set the userId in the connection string directly but it gets picked up as an environment variable when deployed to azure. You can get your connection string from configuration, in my case I have a tenant service to get the connection string since my site is multi tenant
public static SqlConnection Create(ITenantService tenantService, IConfiguration configuration)
{
var tenantConnectionString = tenantService.GetConnectionString();
var connectionStringBuilder = new SqlConnectionStringBuilder(tenantConnectionString);
if (string.IsNullOrEmpty(connectionStringBuilder.UserID))
{
var clientId = configuration.GetValue<string>("AZURE_OBJECT_ID");
if (clientId != null) connectionStringBuilder.UserID = clientId;
}
return new SqlConnection(connectionStringBuilder.ConnectionString);
}
then just use in your startup
optionsBuilder.UseSqlServer(MyUtility.Create(TenantService, Configuration));

InvalidSaml2BindingException: Not HTTP GET Method

I am using ITfoxtec.Identity.Saml2.MvcCore 4.0.7 with TestWebAppCore and TestIdPCore from GitHub ITfoxtec.
When I run this sample from Visual Studio I am not getting any errors and everything works fine. But when I deploy these samples to IIS 10 on Windows server 2019 then I get an error on testing SecurePage, see my error here below.
It looks like ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read method receives an POST request in the Sample program instead of GET.
Can you help me with this exception?
An unhandled exception occurred while processing the request.
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs, line 151
Stack Query Cookies Headers Routing
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs
throw new InvalidSaml2BindingException("Not HTTP GET Method.");
ITfoxtec.Identity.Saml2.Saml2Binding.ReadSamlRequest(HttpRequest request, Saml2Request saml2Request) in Saml2Binding.cs
{
TestIdPCore.Controllers.AuthController.ReadRelyingPartyFromLoginRequest(Saml2Binding binding) in AuthController.cs
return binding.ReadSamlRequest(Request.ToGenericHttpRequest(), new Saml2AuthnRequest(config))?.Issuer;
TestIdPCore.Controllers.AuthController.Login() in AuthController.cs
var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Kind Regards
Ed
I have not seen this error before I'm afraid. It looks like the SAML 2.0 Authn Request is send as POST instead of GET.
The samples for ITfoxtec Identity SAML handels SAML 2.0 Authn Request with Saml2RedirectBinding by default. Do the TestWebAppCore.AuthController Login method in your case use Saml2RedirectBinding?

SID of the target principal could not be resolved.

I delpoyed my web application (which uses LDAP) on windows server 2016. It is throwing below error. Though I am able to access same ADLDS instance using ADSI or C# console application (created utility to test connectivity). But not sure why its throwing error with web application. Please suggest.
Server Error in '/' Application.
**While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.**
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.DirectoryServices.AccountManagement.PrincipalOperationException: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[PrincipalOperationException: While trying to resolve a cross-store reference, the SID of the target principal could not be resolved. The error code is 1722.]
System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o) +570
System.DirectoryServices.AccountManagement.ADUtils.DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx) +133
System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.get_CurrentAsPrincipal() +86
System.DirectoryServices.AccountManagement.PrincipalCollectionEnumerator.MoveNext() +252
System.DirectoryServices.AccountManagement.PrincipalCollectionEnumerator.System.Collections.IEnumerator.MoveNext() +9
System.Linq.<SelectManyIterator>d__22`3.MoveNext() +65
System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) +264
System.Linq.GroupedEnumerable`3.GetEnumerator() +72
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +63
System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +392
System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) +15
Plastin.Common.Security.ADLDSClaimsProvider.SetApplicationClaims() +1012
Plastin.Common.Security.ADLDSClaimsProvider.Initialise() +174
Plastin.Common.Security.ADLDSClaimsProvider..cctor() +238
[TypeInitializationException: The type initializer for 'Plastin.Common.Security.ADLDSClaimsProvider' threw an exception.]
lambda_method(Closure , IBuilderContext ) +81
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +198
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +209
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +165
[ResolutionFailedException: Resolution of the dependency failed, type = "Plastin.Common.Security.IClaimsProvider", name = "(none)".
Exception occurred while: Calling constructor Plastin.Common.Security.ADLDSClaimsProvider().
Exception is: TypeInitializationException - The type initializer for 'Plastin.Common.Security.ADLDSClaimsProvider' threw an exception.
-----------------------------------------------
At the time of the exception, the container was:
Resolving Plastin.Common.Security.ADLDSClaimsProvider,(none) (mapped from Plastin.Common.Security.IClaimsProvider, (none))
Calling constructor Plastin.Common.Security.ADLDSClaimsProvider()
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +329
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +15
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, ResolverOverride[] overrides) +72
Plastin.Common.Security.AuthenticationManager.Authenticate(String resourceName, ClaimsPrincipal incomingPrincipal) +149
Plastin.Portal.MvcApplication.Application_PostAuthenticateRequest() +70
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +87
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +21
System.Web.Util.ArglessEventHandlerProxy.Callback(Object sender, EventArgs e) +56
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Finally we fixed this issue and my apologies I am getting late to answer this question. After lots of debugging we identified that our web application was throwing this error while getting members of ADLDS group. It was unusual as same application was working on other server. So we decided to captured network traffic using Wireshark. Wireshark capture indicated that connectivity between LDAP server and application server was blocked over SMB port 445. So we get our Network team to open port 445 which fixed the issue.
This error seems very generic error and could be other reasons for this error in your scenario but using network traffic capturing tool (like wireshark) at early stage of investigation might help you to troubleshoot these kind of issue quickly.

WCF Can't Open MSMQ Queue: Access is Denied

We have a Windows Service which uses WCF to reads messages from an MSMQ queue. Recently, the service won't start because it can't open the queue:
Running WcfHost, service contract IWcfService. :
System.InvalidOperationException: There was an error opening the queue. Ensure
that MSMQ is installed and running, the queue exists and has proper authorization
to be read from. The inner exception may contain additional information. --->
System.ServiceModel.MsmqException: An error occurred while opening the queue:
Access is denied. (-1072824283, 0xc00e0025). The message cannot be sent or
received from the queue. Ensure that MSMQ is installed and running. Also ensure
that the queue is available to open with the required access mode and
authorization.
at System.ServiceModel.Channels.MsmqQueue.OpenQueue()
at System.ServiceModel.Channels.MsmqQueue.GetHandle()
at System.ServiceModel.Channels.MsmqQueue.SupportsAccessMode(String formatName, Int32 accessType, MsmqException& msmqException)
--- End of inner exception stack trace ---
at System.ServiceModel.Channels.MsmqVerifier.VerifyReceiver(MsmqReceiveParameters receiveParameters, Uri listenUri)
at System.ServiceModel.Channels.MsmqTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
at System.ServiceModel.ServiceHostBase.InitializeRuntime()
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at WcfHost`2.Open()
We've double-checked the queue's permissions and they haven't changed. We've run ProcMon and aren't seeing any access denied events. We don't know what changed to cause this error.
Why can't WCF open this queue?
You can try turn off RPC request from queue settings?

BizTalk & WCF Service: Couldn't find type for class System Diagnostics.TextWriterTraceListener?

I created a simple orchestration to call a WCF service and get response from it. Web service method is very simple:
string GetSimple(int value)
BizTalk monitors a folder and receives activation message using FILE adapter from there, then constructs proper message and calls the web service. But fails with this exception:
Error Description: System.Configuration.ConfigurationErrorsException: Couldn't find type for class System Diagnostics.TextWriterTraceListener.
Server stack trace:
at System.Diagnostics.TraceUtils.GetRuntimeObject(String className, Type baseType, String initializeData)
at System.Diagnostics.TypedElement.BaseGetRuntimeObject()
at System.Diagnostics.ListenerElement.GetRuntimeObject()
at System.Diagnostics.ListenerElement.GetRuntimeObject()
at System.Diagnostics.ListenerElementsCollection.GetRuntimeObject()
at System.Diagnostics.TraceSource.Initialize()
at System.Net.Logging.InitializeLogging()
at System.Net.Logging.get_On()
at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
at System.Net.WebRequest.Create(Uri requestUri)
at System.ServiceModel.Channels.HttpChannelFactory.GetWebRequest(EndpointAddress to, Uri via, NetworkCredential credential, TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.GetWebRequest(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.GetWebRequest(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.GetWebRequest(EndpointAddress to, Uri via, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.BeginSendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Dispatcher.RequestChannelBinder.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.StartSend(Boolean completedSynchronously)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.Begin()
at System.ServiceModel.Channels.ServiceChannel.BeginCall(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, TimeSpan timeout, AsyncCallback callback, Object asyncState)
at System.ServiceModel.Channels.ServiceChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.ServiceChannel.BeginRequest(Message message, AsyncCallback callback, Object state)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.Channels.IRequestChannel.BeginRequest(Message message, AsyncCallback callback, Object state)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.SendRequestMessage(IBaseMessage bizTalkMessage, IRequestChannel channel)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.SendMessage(IBaseMessage bizTalkMessage)
Exception type: XlangSoapException
Source: Microsoft.XLANGs.BizTalk.Engine
Target Site: Void VerifyTransport(Microsoft.XLANGs.Core.Envelope, Int32, Microsoft.XLANGs.Core.Context)
The following is a stack trace that identifies the location where the exception occured
at Microsoft.BizTalk.XLANGs.BTXEngine.BTXPortBase.VerifyTransport(Envelope env, Int32 operationId, Context ctx)
at Microsoft.XLANGs.Core.Subscription.Receive(Segment s, Context ctx, Envelope& env, Boolean topOnly)
at Microsoft.XLANGs.Core.PortBase.GetMessageId(Subscription subscription, Segment currentSegment, Context cxt, Envelope& env, CachedObject location)
at Orch.Orc.segment1(StopConditions stopOn)
at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)
I couldn't find TextWriterTraceListener. Where is it? How to get rid of this exception?
It seems there's a problem with the config file of the WCF service or BTSNtSvc.exe.config. BizTalk seems to be sending the correct request.
Most likely, your config around logging messages from WCF is having issues or BTSNtSvc.exe.config having incorrect parameters around logging.
You may want to call the service from standard .net client to narrow down the problem.
HTH