How to access the database Remotely through IIS? - c#

I have used the ASP.net with C#. I want to access the SQL Server database through web server. When executing my application from development area it's working but after deploy the application to the IIS server it shows the following exception:
CREATE DATABASE permission denied in database 'master'. An attempt to
attach an auto-named database for file D:\newtest\newtest.mdf failed.
A database with the same name exists, or specified file cannot be
opened, or it is located on UNC share.
I have used the following connection string to attached with database
Data Source = .\\SQLEXPRESS;AttachDbFileName=databasepath; Integrated Security=true
How do I access the SQL Server database Remotely through IIS?

Although the answer by Sanjay is correct, it doesn't really explain why you're getting the permission denied.
Code running in ASP.NET / IIS runs as a specific user, as defied in the worker process' config. For IIS 6 [Server 2003] (and below, I think) the default was NETWORK SERVICE for IIS 7+ [Server 2008], the default behavior is to run as a special application pool user IISAPPPOOL\yourAppPoolName.
If you grant the requisite permissions on your database for the correct user account(s) -- you should be able to get around the error and still use integrated security.
As an aside, it is generally a good idea to give the most restrictive (yet still operable) set of permissions on your database. CREATE DATABASE requires a pretty high permission level (I don't remember what off the top of my head.) If you grant that to your IIS application, you run a significant risk of allowing a less than honorable user taking control of your database system and wreaking havoc on it.

Hey Create Credential with SQL server and update your config file
connectionString="Data Source=Abcl\SQLEXPRESS;Initial Catalog=master;User ID=sa;Password=pwd12" providerName="System.Data.SqlClient"
if your are using db file like mdf
Pls use like this
connectionString="AttachDbFilename='C:\Documents and Settings\nmartin\My Documents\PS_Upload\TimeTrack\src\TimeTracker\TimeTrack\App_Data\ASPNETDB.MDF';Integrated Security=True; User Instance=True"

They key is that you've used Integrated Security=True in your conneciton string.
When you run your project in your development environment, the web application usually runs as your local user account. Furthermore, your account is usually a privileged user (admin) on the local SQL instance.
On your deployment server, IIS usually runs as a local machine account (or an account provisioned for your AppPool). That account usually doesn't have any special privileges on the SQL server instace.
As debracey points out, you normally don't want to have your app's SQL privileges high enough to cause any harm (even if it's an honest mistake on your part). One common pattern to avoid tihs is to have two separate SQL accounts for your app:
A high-priviledged account for creating and modifying your database schmea (e.g. db_owner role)
A limited-privilege account for accessing your database while your app runs (e.g. db_datareader and/or db_datawriter role)

Related

Login fails with C# application / SQL Server database installed in a different machine

I created a desktop application which runs with SQL Database. In my machine installation runs perfect. When installing in other machines it do not. Message is:
Cannot open database “verticaladminmod” requested by the login. The login failed. Login failed for “Fina-PC\Fina”
My machine:
Name “MI_PC-PC”
Owner: “MI_PC-PC\MI_PC”
Database: “verticaladminmod”
Connection string:
Data Source=localhost;Initial Catalog=verticaladminmod;Integrated Security=True
Windows 7 64 bit
SQL Server 2014 Express, instance “SQL Server (MSSQLSERVER)”
Other machine installation:
Name “FINA-PC”
User Name: “Fina-PC\Fina”
Windows 7 32 bit
SQL Server 2012 Express, instance “SQL Server (MSSQLSERVER)”
Already understand it should be a matter of credentials, but after several attempts could not get to make it work. Need specific orientation with detailed steps if possible in order to configure where needed looking forward to resolve this issue and understand it in depth as well. Thank you so much!
First, the connection string needs to point at the correct machine (FINA-PC rather than localhost). In some cases you need an instance there, as well (ie FINA-PC\MSSQLSERVER), but with the default instance you can skip the instance name. This is why localhost worked in the original connection string.
Once that is fixed, we can talk about authentication. If you want integrated security to work across machines you also want to have an Active Directory domain. If you don't have an Active Directory domain, you want to switch to SQL authentication.
SQL authentication requires you to create a user ("login", in Sql Server parlance) in the database with it's own username and password you can put in the connection string. Do not use the sa account for this. You must also then be very careful with how you store the connection string, or any decompiler will show the credential and provide full access to your DB. Once you have the new login and connection string, you must also grant permissions for the account to do the operations you need within your database.

Entity Framework Connection via Task Scheduler connects as NTAuthority/Anonymous Logon

I have a Console Application (C#) that connects to a database and sends some emails. It runs fine when a user debug in Visual Studio, but when I copy this to a server and run as a Service Account domain\AcctNotWorking I get the error below. If I switch the account that runs the Scheduled Task to my domain\login it works fine. Why is the service account trying to login as NT AUTHORITY\ANONYMOUS LOGON and any ideas how to fix this? The domain\AcctNotWorking is an admin on the server and has the appropriate permissions in SQL Server.
System.Data.Entity.Core.EntityException: The underlying provider
failed on Open. ---> System.Data.SqlClient.SqlException: Cannot open
database "MyDatabaseName" requested by the login. The login failed.
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
Connection String: add name="ApplicationEntities" connectionString="metadata=res://*/ApplicationEntities" .csdl|res://*/ApplicationEntities" .ssdl|res://*/ApplicationEntities" .msl;provider=System.Data.SqlClient;provider connection string="data source=SQL-Server-Name;initial catalog=DatabaseName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Easy, Integrated Security=True means the current user will attempt to log into the sql server using their windows identity. You either have to 1) create a user for the service to run as, and configure the service to run it under this user, then give this user permissions in the database, or 2) create a sql login with a username/password and use that in your connection string.
Here's a starting point to learn about running a service under a user account
Minimum rights required to run a windows service as a domain account
and here's a starting point for creating sql server logins
https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/create-a-login
Although, honestly, that seems overly complex. All you need to do is login to the server using SSMS and right click on the Security folder and create a new login. It's pretty clear. Then you create a user in the database for that login (same process, but the security folder is under the database). Not too hard. Then switch Itengrated Security=True out for User Id=myUsername;
Password=myPassword;
My preference would be to create a user account on the machine that has no rights other than what it needs to run the service, then create a login & user in sql server for this account that is also locked down to the bare minimum rights required to function. Doing this correctly can be relatively complex if you've never done it before. It is, however, rewarding and will gain you valuable experience you'll use to great effect in your career.
At least, if you go with the quick and dirty sql login method, encrypt your connection string: https://msdn.microsoft.com/en-us/library/89211k9b(v=vs.110).aspx

Entity Framework SQL Connection issues with Integrated Security

On one side I have a Windows service that uses Entity Framework to connect to a SQL Server instance and work with a database there.
On the other side I have a WIX based installer which has a bootstrapper .NET based GUI in which the user can enter connection details to be used in the connection string by the service. In this installer GUI I am also performing a check on the user provided data and check the database connection (using SqlConnection.Open() and even creating/dropping a database).
The issue appears in a workgroup environment, no domain controller present, and when the user chooses Integrated Security as an option. The bootstrapper application successfully connects to the SQL server and performs some operations with it, but then the Windows service fails to connect to the SQL server using Integrated Security. If I follow up by changing that to user and password authentication, the service works correctly.
Is there any way to have the bootstrapper fail connection if the service would fail, or the other way around?
Thanks.
The most likely cause is the user the service is running under and the user the installer is running under are different.
If the User running the installer has access to SQL Server through windows authentication the connection would succeed. Then if the service runs under a different account (Say LocalSystem) the user the service is running under does not have permissions to use integrated security.
The way around this to use a service account which has permissions on the server or use SQL Authentication.
I ran into this recently when deploying a service. The only way to fail the bootstrapper connection would be to run it as the account the service will run under (impersonation is one way to accomplish this) otherwise there is no way you can test the connection correctly.
Since you mention workgroups and no domain controller there may be some pass through going on with the user names and passwords. At one place I worked, on one of the SQL boxes (off the domain) each developer had a local windows account with the same password as their domain account. This allowed a pass through authentication (due to the username and passwords matching) and access to SQL Server. That may be what is going on.

MVC4 published application account logon page does not load

I have created an MVC 4 application using the standard Internet Application template.
I have added some other controllers, views, model and a connection to my own sql database which is working correctly.
When i publish this to a file location to access via my IIS8 on my windows 2012 server the application works except for when i click on logon or register links.
I have not made any changes to the registration or logon parts of the application and as such the Account controller and model have remained the same as has the DefaultConnection string in the webconfig file see below
enter <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-mvcdev-20131010105728;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-mvcdev-20131010105728.mdf" providerName="System.Data.SqlClient" />
I have a couple of registered members and have some views and controllers that require an authorised user to run correctly.
The error i get when i try to access the Account/Logon or Account/Register is:-
Server Error in '/' Application.
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 50 - Local Database Runtime error occurred.
Cannot create an automatic instance. See the Windows Application event
log for error details. )
The 2 event logs are
Unexpected error occurred while trying to access the LocalDB instance registry configuration. See the Windows Application event log for error details.
and
Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.
Has anyone else come across this or have any links to some helpful resolutions?
The application was published to a folder in the Public Documents of my windows server and is being accessed currently of machines on the same LAN
I was also suffering from same problem but there is so small solution for it
just go in iis server than to application pool from which you application is running and in advance setting of application pool we will get the option of Process Model under which there is identity which is by default application pool identity just change it to Local System and your done
And Remember to Put App_Data Folder their in WWW folder of IIS server
If you used the Internet Template for MVC 4 it uses SimpleMembership as the membership provider and automatically wires it up. If you did not make any changes to the basic configuration SimpleMembership is configured in the web.config to use a local database (localDB). SimpleMembership uses EF code-first with lazy initialization. So it checks if the database is available the first time you try to access any of its methods, such logon and registration. If the database is not available it tries to create it. These error messages probably indicate that it could not create this database. If I had to guess you do not have the proper privileges on the server you are deploying to to create a localDB. It is trying to create it in the App_Data folder. Check to make sure that the application has privileges to create files in this folder. The better solution for a production application is to use SQL Server and just change your connections string to point to it instead.

C# with MySQL connector - access denied

I have a remote hosted website with a MySQL database.
I am trying to access that database from a small C# program.
What I've tried:
Referencing the MySQL DLL in the project
Using MySQL connection strings
Disabling my firewall
Adding my IP address to the Remote MySQL Databases in the site's cPanel
What I'm getting:
Access denied for user blabla#mycomputerip in the Visual Studio console
What boggles my mind:
How can I find out if my webhosting service allows remote connections to the DB?
Do I really need to connect with PuTTy to the server and tweak the configs?
^ if so, do I even have access to do that?
LATER EDIT:
Interesting enough. If I do
GRANT ALL PRIVILEGES ON *.* TO 'myuser'#'%' WITH GRANT OPTION;
it throws me this:
#1045 - Access denied for user 'blabla'#'localhost' (using password: YES)
Common sense should tell you that my username is not actually 'blabla'.
LATER LATER EDIT:
I don't have privileges to CREATE USER, nor do I have SSH access via PuTTy or so.
Does this basically mean that it's my hosting's fault that I can't connect from a remote location to the DB?
Have a look at the users in your mysql database. A couple things to check:
With cPanel on shared hosting, if you create a user named blah the actual name of the user in mysql is often unixusername_blah. This is done automatically to prevent MySQL user name conflicts between different cPanel accounts sharing the same MySQL server.
With MySQL you can define which hosts a user is allowed to connect from. Is the new user you defined allowed to connect from your IP?
ETA:
Might want to have a look at the permissions for that user account and make sure appropriate permissions are granted. You can do this by running the following in phpMyAdmin or at the console:
SHOW GRANTS FOR 'something_root'#'localhost'
And compare the grants you see there to what you get here:
SHOW GRANTS FOR 'something_root'#'%'
Finally, depending on your hosting environment you may not have permissions to create new users or expand their privileges enough to be able to do this. This would be particularly likely if you have a shared hosting account.
How can I find out if my webhosting service allows remote connections?
It's better ask your whebhosting proveder, some allows remote connections, other no.
If they allow remote connections you may have to configure which hosts a user is allowed to connect from or, add a wildcard % to allow connections from any host.
Check if your hosting service allows connecting to its database server from outside its network.
Some hosting companies like GoDaddy, by default, don't allow this.
Also, you need to create a database user and assign permissions to it, through your preferred database administration tool.
reset mysql user password and then try again
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html

Categories