Impersonation Issue on IIS7 - Entity Framework Trusted_Connection ASP.NET - asp.net

I'm developing an ASP.NET Application that connects to a Database (on another machine). When I try to connect from my machine there are no problem, when I deploy it on the destination environment, EF returns an exception:
The underlying provider failed on Open.System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) at
My configuration is:
<authentication mode="Windows" />
<customErrors mode="Off"></customErrors>
<identity impersonate="true" />
<security>
<authentication>
<windowsAuthentication useKernelMode="false">
<extendedProtection tokenChecking="None" />
</windowsAuthentication>
</authentication>
</security>
And my connection string is:
<add name="pmgbicopEntities" connectionString="metadata=res://*/copDB.csdl|res://*/copDB.ssdl|res://*/copDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=[NAME]\devde;Initial Catalog=[NAME];Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
If I remove the database instruction the this.Page.User is my current Account (and this is right!), but when I open a new connection via EF I become "Anonymous"
I tried with impersonation like:
WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try
{
ctx = winId.Impersonate();
//EF SOMETHING
}
catch (Exception exx)
{
}
finally
{
if (ctx != null)
ctx.Undo();
}
But I get the same exception "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."
I tried to change the application pool user, tried to impersonate manually but without any success.
The IIS configuration has some kerberos stuff that I tried to Enable and Disable but nothing change.
Do you have any suggestion? Do I have to enable something like "trust" between machines? For my development machine from "fake IIS" I have no problem but my user is enabled on the DB.
Thank you in advance.

What is your end goal here: pass through the user's credentials to SQL or use a predetermined account to connect to SQL?
Here are the settings I've had to configure Kerberos to work (which allows you to use the user's account permissions):
IIS Settings:
-Physical Path Credentials: Application User (pass-through authentication)
-Physical Path Credential Logon Type: Clear Text
-Application Pool ID: Domain\ServiceAccount
-Integrated Windows Authentication: Enabled
-Windows Authentication Providers: Negotiate
-useAppPoolCredentials (found in Configuration Editor): True
SPN created for the ServiceAccount:
SETSPN -L Domain\ServiceAccount
HTTP/Our.WebSiteURL.com
If you want don't want to use a domain service account replace that with Domain\MachineAccount in both the SPN and Application Pool.

Related

Object reference not set to an instance of an object GetDomains call on startup [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
*Note : This is not a null reference duplicate question. It was not so apparent what was causing it and needed deeper investigation.
My site was working fine on my local dev box and then I decided to convert Umbraco 6 from using a embedded database (SDF) to full SQL database (MDF). The database conversion went well using WebMatrix but now after changing the web config to use full SQL the site gets the below error when I run it. I have read through a few help articles online for this but nothing seems to solve my issue. Any ideas? (SQL rights, cache maybe, did I miss a config setting?
I did this basically http://carlosmartinezt.com/2014/03/umbraco-migrate-from-sql-ce-to-sql-server/
Here is my web.config
<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</DbProviderFactories>
</system.data>
<system.net>
<mailSettings>
<smtp>
<network host="127.0.0.1" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
<connectionStrings>
<add connectionString="Data Source=KBURMARK;Initial Catalog=Umbraco;Integrated Security=True" name="Umbraco" providerName="System.Data.SqlClient" />
<!-- Important: If you're upgrading Umbraco, do not clear the connection string / provider name during your web.config merge. -->
</connectionStrings>
Here is the error I am getting
[NullReferenceException: Object reference not set to an instance of an object.]
umbraco.cms.businesslogic.web.Domain.<GetDomains>b__0() +122
Umbraco.Core.Cache.<>c__DisplayClass1`1.<GetCacheItem>b__0() +41
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, CacheDependency dependency) +246
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +159
Umbraco.Core.Cache.CacheProviderExtensions.GetCacheItem(IRuntimeCacheProvider provider, String cacheKey, Func`1 getCacheItem, Nullable`1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +219
Umbraco.Core.CacheHelper.GetCacheItem(String cacheKey, TimeSpan timeout, Func`1 getCacheItem) +339
umbraco.cms.businesslogic.web.Domain.GetDomains(Boolean includeWildcards) +243
Umbraco.Web.Routing.DomainHelper.GetAllDomains(Boolean includeWildcards) +40
Umbraco.Web.Routing.PublishedContentRequestEngine.FindDomain() +365
Umbraco.Web.Routing.PublishedContentRequestEngine.PrepareRequest() +59
Umbraco.Web.Routing.PublishedContentRequest.Prepare() +36
Umbraco.Web.UmbracoModule.ProcessRequest(HttpContextBase httpContext) +738
Umbraco.Web.UmbracoModule.<Init>b__7(Object sender, EventArgs e) +132
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I solved this issue the same way. Set the connection string name="umbracoDbDSN"

Can I use SQL Server CE in a medium trust environment by just deploying the DLLs

I've written an ASP.NET 4.0 application that is using a SQL Server CE 4.0 database. This is all working on my development environment using Medium Trust (same trust config as the hoster). On this machine, I've gone through the install process (downloaded and installed the MSI). I'm now trying to deploy this solution to my web hoster.
The code that is running is (this is a straight out copy of the Altairis Membership Provider:
using (HostingEnvironment.Impersonate())
using (var db = this.connectionString.CreateDbConnection())
using (var cmd = this.CreateDbCommand("SELECT PasswordHash, PasswordSalt FROM $Users WHERE UserName = #UserName AND IsApproved = 1", db))
{
cmd.AddParameterWithValue("#UserName", username);
db.Open();
// Validate password
using (var r = cmd.ExecuteReader()) { .. snip.. }
}
In the instance above, db is DbConnection, and cmd is DbCommand
I'm getting the following error:
[InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods]
System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken
permToken, CodeAccessPermission demand, StackCrawlMark& stackMark,
Int32 create) +0
System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
cap, StackCrawlMark& stackMark) +61
System.Security.CodeAccessPermission.Assert() +28
System.Data.SqlServerCe.KillBitHelper.GetKillBit() +231
System.Data.SqlServerCe.KillBitHelper..cctor() +56
[TypeInitializationException: The type initializer for 'System.Data.SqlServerCe.KillBitHelper' threw an exception.]
System.Data.SqlServerCe.KillBitHelper.ThrowIfKillBitIsSet() +0
System.Data.SqlServerCe.SqlCeProviderFactory..cctor() +41
[TypeInitializationException: The type initializer for 'System.Data.SqlServerCe.SqlCeProviderFactory' threw an exception.]
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeFieldHandle.GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, Boolean&
domainInitialized) +0
System.Reflection.RtFieldInfo.InternalGetValue(Object obj, Boolean doVisibilityCheck, Boolean doCheckConsistency) +180
System.Reflection.RtFieldInfo.GetValue(Object obj) +8
System.Data.Common.DbProviderFactories.GetFactory(DataRow providerRow) +232
System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName) +88
Altairis.Web.Security.DatabaseExtensionMethods.CreateDbConnection(ConnectionStringSettings
settings) in DatabaseExtensionMethods.cs:19
Altairis.Web.Security.TableMembershipProvider.ValidateUser(String
username, String password) in TableMembershipProvider.cs:361
I've used a decompiler to look through the code, and it seems that the internals of SQL Server CE are looking for a registry entry and then trying to do a code Assert().
Is it possible to use SQL Server CE 4.0 in a partial trust environment, by just \bin deploying the DLL ??
Yes, provided your hoster allows it - it is allowed by default in ASP.NET 4.0. Make sure you use assembly version 4.0.0.0 (and not 4.0.0.1). Read more here: http://erikej.blogspot.com/2011/10/sql-server-compact-40-under-aspnet.html

Connection string - Keyword not supported: 'initial catalog'

I am using Webmatrix.data's Database entity to create a database connection, however it doesnt like my connection string. I am running it from MVC ASP.net.
Ive tried changing it to server / database, but still errors the same. Where am I going wrong?
using (var db = Database.OpenConnectionString(#"Data Source=MY-HP\Serv;Initial Catalog=MyDBSQL;User ID=sa;Password=password"))
{
var items = db.Query("SELECT * FROM TaskPriority");
}
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalog'.
check here: Database.OpenConnectionString Method (String, String)
try to specify the provider name as second parameter, from the MSDN example:
var connectionString = "Data Source=.\\SQLExpress;Initial Catalog=SmallBakery;Integrated Security=True";
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
ARRRRHHHHHH!!!!!
This is the second time I've run into this, grrrh - wasted hours on it.
Error:
The server encountered an error processing the request. The exception message is 'Keyword not supported: 'initial catalog;MyDatabase;data source'.'. See server logs for more details. The exception stack trace is:
Stacktrace:
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable
parsetable, String connectionString, Boolean buildChain, Hashtable
synonyms, Boolean firstKey) at
System.Data.Common.DbConnectionOptions..ctor(String connectionString,
Hashtable synonyms, Boolean useOdbcRules) at
System.Data.SqlClient.SqlConnectionString..ctor(String
connectionString) at
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String
connectionString, DbConnectionOptions previous) at
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey
key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions&
userConnectionOptions) at
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey
key) at
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString,
SqlCredential credential)
This was my faulty connection string:
<add name="Production" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog;MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
Looks good right? WRONG
Eventually I spotted the semi-colon here:
Initial Catalog;MyDatabase
To correct it, I used an equal sign:
Initial Catalog=MyDatabase
The correct connection string:
<add name="ConnString" connectionString="Password=Secret;Persist Security Info=True;User ID=MyUserID;Initial Catalog=MyDatabase;Data Source=aquickborwnfoxjumpedover.us-west-2.rds.amazonaws.com,1433" providerName="System.Data.SqlClient" />
You can use the below code
Config file :
<connectionStrings>
<add name="con" connectionString="Data Source=ServerName;Initial Catalog=master;Integrated Security=SSPI;" providerName="System.Data.SqlClient"></add>
</connectionStrings>
cshtmlfile :
var db = Database.Open("con");
var selecteddata = db.Query("select * from movie");
I ran into the error in one of the IdentityServer quickstarts.
Had to replace
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
With
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Using
Microsoft.EntityFrameworkCore.SqlServer
Because obviously my DB was a Microsoft SQL Server and not SQLite.
For me I was getting this error because I was using a templated solution. Unbeknownst to me the template only installed support for sqlite. I had to install Microsoft.EntityFrameworkCore.SqlServer and change the calls in my code from UseSqlite to UseSqlServer.
You need to check your connection string.
I received the error because I had db(instead of 'Database') in my connection string.
"DevConnection": "server=DEL1-XX-XXXX;db=DonationDb;user=sa;password=XXXX"
Updating the above connection string(db to Database) should solve the problem. Below is the working connection string.
"DevConnection":"server=DEL1-XX-XXXX;Database=DonationDb;user=sa;password=QwerXXXX"
I suggest:
You can check your connection string format clearly especialy " and ". In my case this is:
You may try generate db by EF again.

Cookie decryption issue between 2 domains

I am working on some aspnet C# 3.5 webapp. We use IIS7 on our test server.
This webapp communicates with SharePoint 2007 3.0 SP2 by webservices. We have a machineKey in both web.config (the one of the webapp and the one of the Sharepoint site). The two sites are on two different server.
This communication is working fine.
We have also some home-made SSO: the use in the webapp clicks on a link then SharePoint opens in a new window and the user is already logged in.
This SSO is managed by a "shared" cookie in both apps (same name, same domain).
<authentication mode="Forms">
<forms domain="crm.local"
enableCrossAppRedirects="true"
loginUrl="*** url to login page ***"
name=".CrmAuth"
protection="All"
slidingExpiration="true" timeout="200">
</forms>
In SharePoint, we developed a RedirectModule which decrypts the auth ticket from the cookie and log the user.
HttpCookie authCookie = app.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
FormsIdentity identity = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(identity, null);
}
But, all of a sudden, this SSO has broken. When SharePoint tries to decrypt the cookie, an exception is thrown:
[HttpException (0x80004005): unable to validate data]
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo, Boolean signData) +1008
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) +91
System.Web.Security.FormsAuthentication.Decrypt(String encryptedTicket) +246
Nothing has changed on both server. What can be the cause?
What can I do to fix it?
It was due to a change in some reverse proxy box on local network...

Why does this code cause an error?

I have been looking for hours on how to connect to my local SQL database. I can't believe its been this difficult. Anyway, i think I am more on the right track with this code.
<%
Dim myConnection as System.Data.SqlClient.SqlConnection
Dim myCommand as System.Data.SqlClient.SqlCommand
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=dbtest;Integrated Security=True")
myConnection.Open()
%>
However, It still does not work. I don't know where to begin because I also get this message when the page loads:
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
I created a web.config file, and it didn't change anything. I'm so lost. Any help is appreciated!
Stack Trace: [SqlException
(0x80131904): Cannot open database
"dbtest" requested by the login. The
login failed. Login failed for user
'IIS APPPOOL\DefaultAppPool'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
+6244425 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj) +245
System.Data.SqlClient.TdsParser.Run(RunBehavior
runBehavior, SqlCommand cmdHandler,
SqlDataReader dataStream,
BulkCopySimpleResultSet
bulkCopyHandler, TdsParserStateObject
stateObj) +2811
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean
enlistOK) +53
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword,
Boolean ignoreSniOpenTimeout, Int64
timerExpire, SqlConnection
owningObject) +248
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String
host, String newPassword, Boolean
redirectedUserInstance, SqlConnection
owningObject, SqlConnectionString
connectionOptions, Int64 timerStart)
+6260362 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection
owningObject, SqlConnectionString
connectionOptions, String newPassword,
Boolean redirectedUserInstance)
+6260328 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString
connectionOptions, Object
providerInfo, String newPassword,
SqlConnection owningObject, Boolean
redirectedUserInstance) +354
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection
owningConnection) +703
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection
owningConnection, DbConnectionPool
pool, DbConnectionOptions options) +54
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject) +6261592
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject) +81
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) +1657
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) +88
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory
connectionFactory) +6265031
System.Data.SqlClient.SqlConnection.Open()
+258 ASP.index_aspx.__Render__control1(HtmlTextWriter
__w, Control parameterContainer) +71 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter
writer, ICollection children) +115
System.Web.UI.Page.Render(HtmlTextWriter
writer) +38
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +4240
It's here
Cannot open database "dbtest"
requested by the login. The login
failed. Login failed for user 'IIS
APPPOOL\DefaultAppPool'
The App Pool identity account is set up in SQL Server but is not set up in the database dbtest. You get a different error message if you could not connect to the SQL Server instance, but you are connecting for you to get this error message above.1
So, in SQL:
USE dbtest
GO
CREATE USER [IIS APPPOOL\DefaultAppPool] FROM LOGIN [IIS APPPOOL\DefaultAppPool]
Edit:
When you connect to a "database", you actually authenticate 3 times (basically)
To the Windows/domain install hosting the SQL Server Instance (out of scope here)
To the SQL Server instance, where you are a "login" set up SQL Server via CREATE LOGIN
This login maps to zero or more databases as a "user", which is what you needed to do here
In this case, you were set up in SQL Server as a login but not set up in the target database hosted within the SQL Server instance.
Put the CustomError tag and value properly, like:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
This will expose the exact issue to you.
Try to set Data Source=(local)
Have you followed all the instructions and made sure the customerErrors tag in the web.config looks like this:
<customErrors mode="Off" />
And the real error appears to be that the user ASP.Net is running as does not have permission to log in to the database.

Resources