LINQ in ASP.NET -- throws exception when deployed to the server - c#

I am connecting to a SQL Server database via LINQ in my ASP.NET application (returning results to a web service). The problem is that it only returns results when I'm running it in debug/test mode - When I publish the service I get an error telling me
"Login failed for user 'NT AUTHORITY\NETWORK SERVICE' "
So how do I set / provide the credentials I want the site to use to log into SQL Server?
Thanks in advance for any help

You have to set the credentials in the connection string.
It's possible that the connection string to use on the server will be different than the credentials to use during Development. Ask your DBA which credentials you should use.

You are likely not passing a connection string into your DataContext constructor, causing your program to use the connection string in the constructor, which you have been using for development.
So instead of using something like this:
using (var dc = new MyDataContext()) {
...
}
use
using (var dc = new MyDataContext(MyConnectionString)){
...
}
... and take MyConnectionString from your config file...

A few questions first
Is the SQL server on the same machine?
If it's on a different machine is it in a domain?
Are you using a full SQL installation, or SQL Express?
I'm going to assume you're using a full version of SQL, because if you're using SQL Express user instances will not give you this problem.
If it's on the same machine then you need to add Network Service to the list of allowed users in SQL. To do this start SQL Management studio, expand the security folder, then right click on Logins and choose New Login. Click search on the "Login - New" dialog, making sure Windows Authentication is selected then enter Network Service in the object name box and click Ok. Choose the database you want it to access from the drop down list in the Login - new page and click ok. Finally expand out the databases folder and for each database you wish to grant access to expand out security, right click on users, then select the network service login name, give it a name in the dialog of Network Service and grant it the right access by checking the role in the Database role membership list. If you're messing around db_owner will be fine, you will want to lock this down later.
If the SQL server is on a different box and you are in a domain you can run the application pool as a domain user and grant that access on the SQL box. How to do this varies on the version of IIS.
Finally you can use SQL logins and passwords if the SQL server is configured to do this. Create a SQL user and then add them to the connection string like so
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

In your question, it is unclear if you are using a different database between development and production. Typically, you would have (at least) two copies of the database and would set the connection string to point to the correct environment when you deploy typically by changing the value in the web config. Alternatively, you could set the connection string at runtime using the technique Dave mentions.
In your case, I suspect that you are using integrated authentication and getting cought off-guard by SQL security permissions. When you are testing this in your local environment by debugging it in Visual Studio, it runs under your security credential. Most likely, your user account is an administrator (db owner) in the database and thus you have full permission against the database.
When you deploy this, IIS is running under the NetworkService credential. When you try to access the database, the request fails because NetworkService has not been given rights in the database on each of the tables/views/sprocs/etc.
If you have mixed mode set on your server, you can set the permissions on each database object to a SQL user and set the SQL user and password in your web.config. Alternatively, you can change the user account that the IIS process works under and configure the database to work with that user.

Related

Entity Framework Core and Windows authentication on IIS Server

I'm trying to use, for the first time, Windows authentication on my ASP.NET Core 3.1 MVC site to connect to SQL Server using EF Core.
Locally everything is ok (using IIS Express), but on the server, something goes wrong.
My site has "hi,<myDomain/myAccount>!" on the top right of the page, and it is correct, but when I request a page with database query, I get this error:
SqlException: Login failed for user 'MyDomain\MyServerName$'
Why? How do I configure EF Core connection string?
Update:
I can't use form authentication
I don't have a user list table
I can use impersonation (WinAuth? active dir?)
Every user(more can login to site has the access to the sql database
I can change some IIS Server settings
This is the first time i use the winAuth (auto configured by visual studio create project tool => with windows authentication)
"what kind of user is the app pool running under?" i don't know, the default one i think
This is likely an issue having to do with the credentials running the app pool in IIS, and the access rights those particular credentials have. You say you are NOT using impersonation, in which case the request to SQL Server from your app running on IIS needs to be made using a system account that has proper database access. A system account being a singleton account that only exists to run as the "Application Pool Identity" for the app in IIS.
On IIS on your server, what kind of user is the app pool running under? In most cases with Windows Authentication, you want to use a system account of some kind to run the app pool and then give that system account access to the database. If you don't want to use a system account, you would have to use impersonation, and then use an AD Group to give the impersonated users access to the SQL Server Database.
Since you're saying the request to SQL server is coming across as DOMAIN\SERVERNAME, you likely need to change that setting in IIS to set the request to come from a system account, and then give that system account explicit access to the SQL Server database.
You can change this by adjusting your Advanced Settings in IIS and inputting the information (Username/PW) of the account you want to run the app under or "as" in IIS.
Then, add this same DOMAIN\USERNAME account to the Database as a user who can Read/Write/Delete etc. You could also simply add the DOMAIN\SERVERNAME that is being denied in it's request to the database here, if you don't want to use a custom system account.
As for "How to configure EFCore connection string?", this is usually done in the Startup.cs file. There you can input a connection string from your appsettings.json directly with the .UseSqlServer(connectionstring) method.
You access the connection string using Configuration.GetConnectionString("KEY").
Once configured there, you don't need to configure it again (unless perhaps to change from dev/qa/prod environments).

WebApi access to database fails when deployed to IIS

I developing ASP.Net MVC website which uses an ADO.Net Entity Data Model to connect to a MS SQL Server.
To access data it uses WebApis in views called from jquery which use the above datamodel to get data, and it also uses code in the view controller which also uses the same datamodel.
When I run this locally (on the development machine), everything works fine. However, when I deploy it to IIS v10.0 and try to access the website from another machine, it partially works. Calls to the database made using the WebApis fail with a:
HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
Whilst pages that call data access code from the view controller work correctly.
When I look at the error for the WebAPI I see that the following error is produced:
"ExceptionMessage":"Login failed for user 'xxx\yyy-zzz-15$'
I don't know why this login is being used - I would expecting it to be using the 'NT AUTHORITY\IUSR' login, like the data access code from the view controller does.
Any thoughts?
you have two options
in database add that user to NT AUTHORITY\SYSTEM and give it the
permissions to your database.
make new user login in database and give it the
permissions to your database and change the web.config to not be integrated
security and add the user ID and password.
Your problem as it stands is because you are running as a default account - you've then asked that account to access other machines and data. To fix that you need to have it work as an actual account.
To have your webcode run as a user the simplest way is get a functional account from your AD team, and then set the pool for your site to be that AD account, and allow that AD account also the appropriate (eg not sa) to SQL.. As per comment to Mohamed's options above.
Please check the application pool on which your website is running. If the app pool is running on a service account, you need to add same account to your database server and assign proper permissions.
In your connection string, if you don't set the user, it will use the IUSR user.
And the IUSR User will not have enough permission to connect to the database.
I don't recommend to give rights to the IUSR user because this can cause security issues!
Instead, you should define your user id and password in your connection string.
If there is not user that you can use in your server, you can create a new user and give necessary permissions to this user.
here is a simple connection string :
data source=yourServerID;initial catalog=YourDatabaseName;user ID=yourNewUser;password=PasswordOfYourNewUser;
To configure a new user :
https://support.chartio.com/knowledgebase/granting-table-level-permissions-in-sql-server

asp.net web api cannot connect to Azure SQL database with non-admin user

So for security purposes I created a different user on my azure sql server so I can connect to it without giving full admin to the server. But it turns out the web api cannot connect with that user. It can connect with the admin just fine. Also I know the password and firewall are fine cause I'm able to connect with the non-admin account through SSMS which got me really confused. For now I just deployed with the master account. But would be good if I could fix this.
It is a good practice to not to use full privelleges user rather than action based user for each operation like SELECT select_user, Update update_user and so on.
How ever each of these user should be given connection right as well which seems to be not set in your case.
for this go in object explorer
server connection > security > login >
select your user and right click on it and select properties
in general select sql authentication and mention password and also click on status option and make sure that "Permission to connect ..." is enable and login is also

Use a Web Service to Run SQL queries for a Windows Forms Client

I need to use a Windows application running on remote clients that will connect to a web service. The web service will access an SQL database to verify users, and roles, and perform other tasks. I am using ASP.NET Membership to manage the users and roles. I have ASP.NET Membership, and the web service working on the development machine. I have a windows client with a service reference that works when I access methods that do not access the database, but when I try to access a service method that access a database method I get The user is not associated with a trusted SQL Server connection. I get various permissions errors depending on what I am try to fix this, but this is the gist. I don't want the Windows client to need DB permissions. I want it to send a user name, and password to the web service, then the web service wraps Membership.ValidateUser(userName, password)
Can someone tell me how to set this up?
You should consider setting up SQL Server to use SQL and Windows Authentication (mixed mode). It's most likely running in Windows Authentication mode only. You can take a look at this link to get started.
It sounds like, by the way you have it designed, is that you would have to set up an account for each user. In my experience it's best to just create a specific SQL account with the necessary permissions, and have each client use that account. You could specify this in the connection string.
Assuming you have named pipes authentication enabled in SQL, your SQL connection string in your ASP.NET application could be configured to use integrated security (Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;). Then in SSMS, give the appropriate ASP.NET user privileges to the database. The user that IIS uses depends on what version of IIS you're running, and can be seen in the App Pool configuration for the server in question.

Cannot login to local database using web service

I am trying to access my local database using a web service also running locally on the Default Website in IIS7. I previously always used Windows Authentication but I read that to use web services you have to use SQL Server authentication, I have no experience with this but tried it out. I created a new login, but when I try using those credentials in my connection string:
connectionString="Server=.\SQLExpress;Database='SponsorChild';Trusted_Connection=True;User Id=abc;Password=abcpass" name="SponsorChildDatabase"/>
and try using the web service, I get the error:
System.Data.SqlClient.SqlException: Cannot open database "SponsorChild" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\DefaultAppPool'.
So it seems not even the right user is being passed. Moreover, when I try logging in using SQL Management Studio, it also gives me a login error (error 18456 with state 38). I apologize if this is just some rookie mistake, but I'm just starting out with databases and website building and still have a lot to learn. Any help is greatly appreciated.
Trusted_Connection=True uses the Windows credentials and not the provided username and password. The user you've setup in the database doesn't play a role. You either need to use SQL Server auth or authenticate the Windows account the service is running under.
This is a sample connectionstirng not using Windows credentials:
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
To create a SQL Server login that uses SQL Server Authentication (SQL Server Management Studio)
1.In SQL Server Management Studio, open Object Explorer and expand the folder of the server instance in which to create the new login.
2.Right-click the Security folder, point to New, and then click Login.
3.On the General page, enter a name for the new login in the Login name box.
4.Select SQL Server Authentication. Windows Authentication is the more secure option.
5.Enter a password for the login.
6.Select the password policy options that should be applied to the new login. In general, enforcing password policy is the more secure
option.
7.Click OK.
The fact that the database is local probably means you administer it yourself, so here is a manual for setting the sql server authentication.
Check to make sure:
that you have the proper server name in your connection string. Is it really localhost? Or did you perhaps install SQL Server Express and it ended up being (local)\SQLExpress instead??
that the server you're connecting to has a login for User-Desktop\user(check in Object Explorer -> (your server) -> Security -> Logins)
that the database ASPNETDB has a user based on that login so that you can use that database (check in Object Explorer -> (your server) -> Databases -> (your database) -> Security -> Users)
that your admin.aspx page is truly referencing that connection string you've given (ConnectionString1). Is there by any chance a separate web.config in your Admin folder that e.g. has a different connection string, and the admin.aspx page references that connection string instead??

Categories

Resources