I'm trying to hit my intranet website and get it to run a simple sql query as the windows user I'm logged in as.
When I debug through Visual Studio, everything works great. When I hit the webserver though, I get an error from sqlconnection saying, "ERROR:Login failed for user 'YOUR_DOMAIN\YOUR_WEBSERVER_NAME'."
Request.ServerVariables[AUTH_USER]: YOUR_DOMAIN\UserBob
System.Security.Principal.WindowsIdentity.GetCurrent().Name: NT AUTHORITY\NETWORK SERVICE
Page.User.Identity.Name: YOUR_DOMAIN\UserBob
System.Threading.Thread.CurrentPrincipal.Identity.Name: YOUR_DOMAIN\UserBob
So how do I get the SQL query to execute under UserBob?
Here's my setup:
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<identity impersonate="true"/>
<customErrors mode="Off"/>
</system.web>
Webserver is a Win 2008 server with IIS7, Windows Authentication on, Anon Auth off.
Code is simply:
Response.Write("Request.ServerVariables[AUTH_USER]: " + Request.ServerVariables ["AUTH_USER"].ToString());
Response.Write("<br>System.Security.Principal.WindowsIdentity.GetCurrent().Name: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
Response.Write("<br>Page.User.Identity.Name: " + Page.User.Identity.Name);
Response.Write("<br>System.Threading.Thread.CurrentPrincipal.Identity.Name: " + System.Threading.Thread.CurrentPrincipal.Identity.Name);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CarbonDB"].ConnectionString);
conn.Open();
SqlCommand sqlcom = new SqlCommand("dbo.runsomething", conn);
sqlcom.CommandType = CommandType.StoredProcedure;
SqlDataReader sqlDataReader = sqlcom.ExecuteReader();
conn.Close();
Is the SQL Server on a different machine than the web server?
If so, the issue you are running into is related to Kerberos Delegation. Basically, your web server doesn't have the permission/ability to impersonate the end user to another server.
Try this link for more information on delegation.
Be aware that this isn't trivial, and requires assistance from a network admin, as it involves making changes to your Active Directory environment.
If possible, use a service account (such as Network Service) to access the SQL Server.
Erick
Is the site using Integrated or Classic pipeline mode. In IIS7, check the Basic Settings of the website, click Connect As... and make sure that Application user (pass-through authentication) is checked.
Related
I have a very basic ASP.NET web application that is connecting to a SQL Server database (I am using SQL Server 2008 Express). The problem I am having it is very odd: if I set the connection string for the SqlConnection object directly in code, the application works fine, but if I move my connection string to the web.config file, the application fails.
I show you both the variable and the connection section in the web.config to see if you detect any error:
In the variable:
// works fine
string cs = "data source=.; database=myDataBase; integrated security=SSPI";
SqlConnection conn = new SqlConnection(cs);
Now in the web.config:
<configuration>
<connectionStrings>
<add name="myCS"
connectionString="data source=.; database=myDataBase; integrated security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
...
// Now, if I do this in C#, it does not work:
string cs = ConfigurationManager.ConnectionStrings["myCS"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
It tells me that there is already a database with that name. Now, I have read things everywhere. Some guy said that instead of using "database" in the connectionString, I could use "initial catalog" and all would be fine. Well, it wasn't fine... I have the same problem... Does anyone know what I am doing wrong? Why is working in one place and not in another? If the connection string was wrong, it should fail in both places, and it is only crashing in the webConfig file... Thanks very much...
If you are running this from Visual Studio, have you tried stopping the Dev Server (running in your system tray) and trying? the Web.config file is normally cached and could cause issues.
I have developed a web apllication in asp.net with its connection String in web.config file and working very well in localhost. But when i deployed to hosting server using windows shared hosting it fives the error
Logic failed for user anama76
where anama76 is my domain user.My database userName is anama_Muneeb. I am finding it difficult to know that why connection string is using the domain user to connect to Db.
I have used connection in web.config to make sql server authentication
What is the solution
Your connection string must match the user name:
<add
name="ConnectionString"
connectionString="Data Source=your_database_server;Initial Catalog=your_database_name;User Id=anama_Muneeb;Password='your_password';"
providerName="System.Data.SqlClient"/>
I'm trying to connect remotely and I have the following connection string on my MVC3 using EF4 ctp5 code first
<add name="ApplicationServicesX"
connectionString="provider=System.Data.SqlClient;provider connection string='Data Source=asc-svr2;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />
and it gives an error
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
and
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
my controller looks like this
public ActionResult Index()
{
var post = cmsDB.Posts.ToList();
return View(post);
}
When I run the code on my local machine no problem at all but when I get into
remotely connecting into SQL Server 2008 the problem arises.
Thanks a lot for any help.
Your connection string is configured to use Integrated Windows Authentication (Integrated Security=True). For this to work make sure you have enabled NTLM in IIS. Also if the SQL Server is on a different physical machine than the web server you might need to configure delegation. As an alternative you could use SQL authentication with a fixed account:
<add name="ApplicationServicesX"
connectionString="provider=System.Data.SqlClient;provider connection string='Data Source=asc-svr2; Initial Catalog=AdventureWorks;User Id=foo;Password=secret;Connection Timeout=60;multipleactiveresultsets=true'"
providerName="System.Data.EntityClient" />
I have an ASP.NET app using built-in Membership functionality. As such, I have a connection string in my web.config that looks like this:
<add name="MembershipSqlServer" connectionString="Data Source=servername;Database=aspnetdb;uid=user;pwd=password;" />
When working on my dev machine, everything is peachy keen. But when I move things to the web server (which also happens to run the SQL Server), I get this error when User.IsInRole() is called:
System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.
F$%*&!! Why is it attempting to connect in this way? Why isn't it using user/password from the connection string? Web.config is identical on dev and server, I am using the DB on the server during development.
OK, I figured it out... only 35 minutes. :P
Long story short: There are two parts to asp.net membership… a membership provider and a ROLE provider. Why you’d ever want these two things separated, I don’t know… But my web.config wasn’t specifying the role provider and connection string, so it was defaulting to the settings in machine.config (aka LocalSqlServer connection string).
So all this time, my app users were on the server... but the roles were stored in a local .MDF file in App_Data. Ugh.
What does the membership providers section in your web.config look like? Is it possible that you left out the connectionStringName attribute? In which case, I believe it would be trying to connect to the database on your local machine using integrated security.
The membership providers section in your web.config should look something like:
<membership defaultProvider="SqlProvider">
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MembershipSqlServer"
...
/>
</providers>
</membership>
Do you see this <authentication mode="Windows" /> in your web.config? And your other connectionString uses Integrated Security=True; On your Sql server in order to use windows authentication you must have a Login(on the server) for the windows user or group as well as have an associated user in the database.
The simple but not suggested fix would be to create a login for 'NT AUTHORITY\NETWORK SERVICE'
on you sql server and then a user in your specific database for that maps to that login.
The secure way is to do this for each of the network security groups that need to access the sql server so you can manage the group permissions independently.
i think the answer is that :
public static string ConnectionString(SPSite site)
{
var connectionStringField = BaseMembershipProvider(site).GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (connectionStringField != null)
{
return connectionStringField.GetValue(BaseMembershipProvider(site)).ToString();
}
else
{
return "";
}
}
it worked for me with out any Error
thanks babania
I can not seem to get sql server to recognize my credentials.
Asp.net recognizes me when I login but when I execute a sql command I get a login failed message.
The IIS server and SQL server are on different machines.
There are other applications the IIS server which are able to authenticate to the sql server. I believe the Active Directory settings are correct. I am investigating what I am doing differently.
I must be missing something.
I check the IIS settings
The web config is set to impersonate.
Below is the relevant information. If anyone has any idea as to what I missed or am doing wrong I would appreciate some help.
IIS Settings:
'Integrated Windows authentication' is checked
'Enable anonymous access" is not checked
Web Config
<authentication mode="Windows"/>
<identity impersonate="true"/>
<authorization>
<deny users="?" />
</authorization>
Page_Load Code:
Dim winId As IIdentity = HttpContext.Current.User.Identity
TextBoxMessage.Text = winId.Name + Environment.NewLine
Dim cnn As SqlClient.SqlConnection
Try
Dim sql As String = "*****"
cnn = New SqlClient.SqlConnection("Data Source=*****;Initial Catalog=****;Integrated Security=True")
cnn.Open()
Dim cmd As New SqlClient.SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
TextBoxMessage.Text += ex.Message
cnn.Close()
End Try
Output:
Domain\UserName
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
This is key = The IIS server and SQL server are on different machines. You're facing the classic double hop issue. Think of it in this way:
You access the web application under your credentials
IIS in this case has to present who you say you are to the SQL Server
IIS says, "Why hello SQL Server, I'm passing on Tony's kerberos creds, they are legit"
SQL Server says, "Hmmm, IIS I'm not sure I trust you, I need proof that you are trusted to present these credentials to me".
Thus once you enable delegation as mentioned by Remus, your SQL Server will trust the credentials your IIS server is presenting on your behalf.
In terms of security, under delegation, it would be wise to choose:
Trust this computer for delegation for specified services only | Use Kerberos only | and then underneath the "Services to which this account can present delegated credentials" make sure you explicitly set only the server/port you need.
You also need to enable constrained delegation:
Enabling Constrained Delegation
How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0
Windows Server 2003 Constrained Delegation (IIS 6.0)
Are your ISS server and SQL Server running on the same machine?
If not, Active Directory has to be configured to allow your IIS server to impersonate your accout towards the SQL Server. See How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0.
Long story short: IIS server should have "trusted for delegation" checkbox checked in Active Directory.
You need to set you credentials in Application Pool.
- Open IIS
- Select Application Pools
- Enter the name, select .Net framework version and click OK
- Select the new added application pool and click on Advanced Settings..
- In the Process Model section click on Identity - choose custom account and enter the AD username, password, confirm password and click OK
- Select your application and in the Basic settings choose your application pool just created.
Hope this helps