WCF Service Error accessing DB - c#

I have a WCF Service running under IIS 7.0. The app pool identity is set to a user account lets call it "MyDomain\MyAcc." I have given "MyDomain\MyAcc" login permissions to the SQL 2005 Server, and the two DBs that it uses on that server.
When I try to invoke one of the WCF methods I get the following in my logs:
"Login failed for user 'MyDomain\MyAcc'..." I have tried removing and re-adding that user on the SQL Server.
I also tried accessing the DBs from Management Studio running as "MyDomain\MyAcc" and that worked.
What am I missing?

Finally Figured it out, we are using LINQ to SQL and the last guy who checked the code in commented out the code that we used to pass in the connection string from the web.config file. So it was using the connection string from the dbml file instead. That connection string was pointing to a DB that the user account did not have access to.

Related

C# MySql error: MySql.Data.MySqlClient.MySqlException [duplicate]

Trying to connect to MySQL on my web host, using Connector/Net C#/WinForms in Visual Studio 2012 Update 3, but getting the below error message:
Authentication to host '1.1.1.1' for user 'username#mydomain.com' using method 'mysql_native_password' failed with message: Access denied for user 'username#mydomain.com'#'2.2.2.2' (using password: YES)
string connectionString = "SERVER=1.1.1.1;PORT=3306;DATABASE=databaseName;UID=username#mydomain.com;PASSWORD=mypassword;";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
I am connecting remotely, have whitelisted my IP (and even temporary whitelisted all (%) to test), triple checked the username and password and IP.
I originally tried the username without the domain ( username rather than username#mydomain.com) but it gave me the below error:
Authentication with old password no longer supported, use 4.1 style passwords.
Any assistance would be much appreciated, thanks!
Its problem of 'Remote Database Access Hosts'.
"You can allow external web servers to access your MySQL databases by adding their domain name to the list of hosts that are able to access databases on your web site."
MySql access is not granted to IP address of the system at which application is running.(in your case its '2.2.2.2' ).
Note:- '2.2.2.2' is your public IP address.
Two possible things:
MySQL is case sensitive make sure that the case of Database= in your connection string matches with the actual database name
You may have to grant privileges to the user.
I hope this help you.
Check your application settings file (or wherever you have stored the connection string).
In my case the application was using the old connection string (which was not valid). I was assuming that the change I made in the code of the settings file is reflected to the designer (of the settings file). But it was not!
After creating a new user in MySQL, in MySQL Workbench "Test Connection" will succeed but the C# MySqlConnection.Open() will throw the same exception and message as the question (tested with localhost and 127.0.0.1 and the local ip address).
The reason is that MySqlConnection.Open() will somehow use SELECT privilege, and you need to at least enable the SELECT privilege for the new user. The error message is misleading.
This might be related to the case of specific Membership SQL Server based instructions on ASP.NET 4.5, workaround is to create new membership in web.config, drop mvc 4 AccountControler and use old from MVC3 more here or in the internet:
http://www.nsilverbullet.net/2012/11/06/using-mysql5-as-membership-backend-for-aspnet45-mvc4-application/
In my case updated password was not used. I just generated the password using Password Generator and copy it but forgot to click Change Password.
Also check the user is added to the database and has Privileges.
For me, using the actual IP address instead of the domain name solved the problem
While Whitelisting my Ip on cpanel i had accidentally put a space in there after my ip address.[Should have been handled by them]
I added the ip again and it worked.
In my case, the problem was misleading as well.
Had quite a few windows terminals running "the same" .net app all connecting to a remote MySQL server (installed in a windows server machine). However, only one always popping the specific error when anyone clicked to run the .net application. ODBC test connection passed successfully, and no matter if the error popped, when presing OK the application continued loading successfully finally and then worked fine.But again afterwards , when anyone tried to run in for the first time the message appeared. and I repeat only in this specific terminal! The fix finally came when I noticed, that it was only in this specific terminal with the problem that we had forgotten DHCP enabled! and "although it was given always the same IP" from our IT policies, however it only worked when we disabled DHCP and set this IP, SUBNET and GW, as fixed !
Check with a program like Navicat that the mysql server user has a native password. Everything is correct but if you are getting this error check the version of the link DLL
This error; Mysql.Data.dll and Mysql Server version mismatch error. Download and install an older version
https://downloads.mysql.com/archives/c-net/
Mysql Version < 4.5
Mysql.Data.Dll version= 6.0.3

How to check if a windows user has access (Windows Integrated Security authentication) to SQL Server Analysis Services (SSAS) Server via impersonation

For a SQL Server instance, to check if a windows user is present and has any access or not one can try various ways as detailed here.
I'm looking for something similar for SQL Server Analysis Services (SSAS) server.
I went into properties of SSAS Server from right-click context menu and on Security tab I can see that there are several windows users already configured:
Is there any way to check from a client application (written in C#) by making some sort of test connection or does SSAS also maintains some metadata database of its own like master database in SQL Server instance (DB engine) which can be queried. I checked the Databases node in SSAS server but I don't see any default databases there:
In the client application I'm working upon, I've windows user name and password as input. In my client application there is a simple winform with two text boxes to take AD user name and password which need to be connected to a SSAS Server. My gut feel is that password is of no relevance here as SSAS supports only Windows integrated authentication mode. My client application would be running under an account which already has access to SSAS server I'm trying to connect.
Update: After getting help from #Vaishali, I'm able to figure out that it is possible to make a test connection to an SSAS server using ADOMD.Net.
Now, the problem here is that the connection string implicitly uses the AD account of the user with which I'm running the client application to connect to the SSAS server. I don't think it would be possible mention an windows AD account user name and password explicitly in the ADOMD.Net connection strings while using Windows Integrated authentication. Even connection strings of SQL Server don't allow mentioning the windows username and password explicitly in the connection string as mentioned here.
Update 2: I have got a lead from one of my friends that it is possible to fire some MDX query on SSAS to get user access details.
Update 3: SSAS server supports only Windows Integrated Security mode of authentication unlike SQL Server DB engine which also supports userid-password based SQL authentication. So, some form of impersonation would be required to fire MDX queries on behalf of other user for which I'm trying to check access on SSAS server through Windows Integrated Security only.
Hmphh...It was quite a journey to really be able to nail it through ADOMD.Net.
Core methodology: The core philosophy is the fact that connection to SSAS server supports only Windows Integrated Security based authentication. The SQL authentication like we do for sa user in SQL Server isn't supported in SSAS.
So, the basic idea was to try to connect to the SSAS server using Windows Integrated Security based authentication and fire an MDX query in the context of the user we are trying to check. If the query gets executed successfully then the user has access. If the query execution returns an error/exception then the user doesn't have access.
Please note that just to be able to open a connection to the SSAS server is not an indicator of user-access due to reasons described here. You must fire a query to check access.
For ADOMD.Net until v12.x:
Now, we know that Windows Integrated Security based authentication always takes the user details from the user-context under which the application/process is running. You can not pass the user credentials in the connection string of ADOMD.Net connection. Here is the code I wrote to accomplish it. You need to refer to Microsoft.AnalysisServices.AdomdClient.dll in your C# project.
using Microsoft.AnalysisServices.AdomdClient;
public static int IsSsasAccessibleToUser(string ssasServerName)
{
var hasAccess = 0;
try
{
using (var adomdConnection = new AdomdConnection($"provider=olap;datasource={ssasServerName};Catalog=myDatabaseName"))
using (var adomdCommand = new AdomdCommand())
{
adomdCommand.CommandText = "SELECT [CATALOG_NAME] AS [DATABASE],CUBE_CAPTION AS [CUBE/PERSPECTIVE],BASE_CUBE_NAME FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE = 1";
adomdCommand.Connection = adomdConnection;
adomdConnection.Open();
adomdCommand.ExecuteNonQuery();
Log("ExecuteNonQuery call succeeded so the user has access");
hasAccess = 1;
}
}
catch (Exception ex)
{
Log("There was an error firing query on the database in SSAS server. so user doesn't have access");
}
return hasAccess;
}
Now, to leverage Windows Integrated Security based authentication we can run this code in two ways:
Out-Proc Impersonation : Put this code inside a console application. Use the "Run as different user" option in the context menu when we right click the exe. Put the credentials of the user Y (let's say) so that application starts in the context of user Y for which we need to validate the access on SSAS server. ADOMD.Net will use user Y's identity while connecting using Windows Integrated Security for SSAS server. If code succeeds the user has access.
In-Proc Impersonation: The other case could be that you are running the application as user X but you want to test the access of user Y. Here effectively you require in-place impersonation while running the above code. For achieving it I used a famous NuGet package "Simple Impersonation" which uses the default .Net library classes WindowsImpersonationContext and WindowsIdentity . Creator of this NuGet package had first posted a great answer here.
Observation in SQL Server Profiler: After you've impersonated user Y, you will clearly see the MDX query getting fired in the context of user Y if you capture the session as shown below:
Caveats and concerns:
One issue that I faced while using this in-proc impersonation is that it doesn't work if the SSAS server is located on the same machine where the application code is running. This is due to the inherent behavior of native LogonUser API (using LOGON32_LOGON_NEW_CREDENTIALS LogonType) which is called during impersonation calls by the NuGete package. You can try other logon types as detailed here which suites you need.
You require password of the user as well along with the domain name and user name to do impersonation.
For ADOMD.Net v13.x onwards
Then, I came across this ChangeEffectiveUser API documentation on MSDN here. But, intellisense wasn't showing this API. Then I found out this API got added in ADOMD.Net with SQL Server 2016 release. There are various ways to get the latest release:
C:\Program Files\Microsoft.NET\ADOMD.NET\130\Microsoft.AnalysisServices.AdomdClient.dll
I'm not sure who dumps this file at this location. Is it part of Microsoft.Net extensions or SQL Server installation.
In Installation folder of Microsoft SQL Server. I got it at path - C:\Program Files\Microsoft SQL Server\130\Setup Bootstrap\Update Cache\KB3182545\ServicePack\x64\Microsoft.AnalysisServices.AdomdClient.dll
NuGet package here. For some weird reason best known to MS the NuGet package of v13.x of ADOMD.Net has been named Unofficial.Microsoft.AnalysisServices.AdomdClient. Not sure why they introduced a separate NuGet package with Unofficial prefix when this should have been simply the next version of the already existing NuGet package Microsoft.AnalysisServices.AdomdClient present here.
So the new API ChangeEffectiveUser present in latest version on AdomdConnection clas can be used easily to impersonate any user as below:
adomdConnection.Open();
//impersonate the user after opening the connection
adomdConnection.ChangeEffectiveUser("domainName\UserNameBeingImpersonated");
//now the query gets fired in the context of the impersonated user
adomdCommand.ExecuteNonQuery();
Observing Impersonation in SQL Server Profiler: Although one peculiar observation I had in the SQL Server Profiler is that the logs of query being fired still shows the name of the original user with which your application process is running.
So to check whether impersonation is happening or not I removed the access rights of the user domainName\UserNameBeingImpersonated from SSAS server. After that, when I ran the above code again then it resulted in exception whose message clearly states that - the user domainName\UserNameBeingImpersonated doesn't have permission on the SSAS server or the database doesn't exist. This error message clearly suggests that impersonation is working.
Advantages and Backward compatibility of this approach:
Although the API is very recent as it came up with SQL Server 2016 but I was able to use it successfully with SSAS server 2014 as well. So it looks fairly backward compatible.
This API works irrespective of whether your SSAS server is local or remote.
You just require the domain name and user name for doing impersonation. No password require.
What to do if we simply want to check the access on the SSAS server without involving any database present on the SSAS server?
Change the connection string to not involve any database. Remove the Catalog key as following connection string - "provider=olap;datasource={ssasServerName};"
Fire the following query instead to check access - SELECT * FROM $System.discover_locks in the code snippet shown initially in the post.
If you wish to check if user has accessibility to SSAS server, one option you can try with C# is: try connecting SSAS with given user credential, if you succeed, you have access.
If you are looking for roles and security mapped to individual cube database, following link will be usefull.
http://www.lucasnotes.com/2012/09/list-ssas-user-roles-using-powershell.html#comment-form
C# code lines:
import library Microsoft.AnalysisServices.AdomdClient;
and code lines would be:
DataSet ds = new DataSet();
AdomdConnection myconnect = new AdomdConnection(#"provider=olap;datasource=.\SQL20f12");
AdomdDataAdapter mycommand = new AdomdDataAdapter();
mycommand.SelectCommand = new AdomdCommand();
mycommand.SelectCommand.Connection = myconnect;
try
{
myconnect.Open();
}
catch
{
MessageBox.Show("error in connection");
}
Hope this works for you.

Azure Mobile Service login error with database and "master" user

I've been using Azure Mobile Services with my apps without much issue, but then today when I tried to pull from the service I get this error:
Exception=System.Data.SqlClient.SqlException (0x80131904): Cannot open
database "master" requested by the login. The login failed. Login
failed for user 'JVlSvKwDpdLogin_*****'.
I've never had this issue come up before, and I'm only connecting to my mobile service in code like this:
public static MobileServiceClient MobileService = new MobileServiceClient(
"https://<webservicename>.azure-mobile.net/",
"<YOUR-API-KEY-HERE>"
);
Before this error happened, I never supplied a username or password. I've seen some solutions where they've created a user for the database but I don't want to create one right now since we're still in testing and I'd rather be able to use the service without one for now. Is this an issue with mobile service, or an issue with the database?
UPDATE
As suggested by Matt's answer below, I found the MS_ConnectionString in the Azure portal. I then connected to the 'master' database on my Azure SQL server and searched for the login above. I changed the password to the one found in the connection string using
ALTER LOGIN <login> WITH password='<password-found-in-connection-string>';
But now I get this error:
Exception=System.Data.Entity.Core.ProviderIncompatibleException: An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure. ---> System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: Login failed for user 'JVlSvKwDpdLogin_*******'.
I haven't change anything with the connection string or the web.config file for my AzureMobileService project.
web.config:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source= (localdb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-CoverageTool.AzureMobileService-20140910083006.mdf;Initial Catalog=aspnet-CoverageTool.AzureMobileService-20140910083006;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
MobileContext:
private const string connectionStringName = "Name=MS_TableConnectionString";
public MobileServiceContext()
: base(connectionStringName)
{
}
Connection String
Data Source=*****.database.windows.net;Initial Catalog=sbpconsulting_db;User ID=*******Login_sbpconsulting;Password=**************;Asynchronous Processing=True;TrustServerCertificate=False;
This error could also appear if your Entity Framework database initializers are not compatible with the permissions of the database user that your Azure Mobile Service is using.
For example, when you create database for a Azure Mobile Service, Azure automatically creates a DB user for your service. This user does not have admin permissions - it can generally read and write data to a table. In that case, if you are using DropCreateDatabaseAlways DB initializer your user will not have sufficient permission to actually drop the database and you may see the error that you have mentioned.
There are new initializers that were introduced to work with limited set of permissions:
ClearDatabaseSchemaAlways - use instead of DropCreateDatabaseAlways
ClearDatabaseSchemaIfModelChanges - use instead of DropCreateDatabaseIfModelChanges
I can only think of one thing that may be the problem. Windows Azure Databases only allow specific ip addresses that you have white listed before hand.
So if you are trying to run your app from a different internet connection or if your ip address has changed then that might be your issue.
Try accessing your database directly on your Azure Management Console and allow your ip address access to the database server.
Azure always needs authentication so check your applications app.config / web.config file for credentials.
More code-based information would have been helpful to make this answer more than a shot in the dark.
Do you control the SQL login? Do you have other databases hosted on the same SQL Azure server?
That error is happening on the backend between your service tier and the database and won't be impacted by anything in the client application(s).
The account setup in the portal doesn't have the permissions it needs. Either you have found a bug, someone has revoked the permissions for that user, or the password has changed.
Based on the error message, I'd say it is the latter issue and you need to find out what the password is and make sure it is in sync with the MS_TableConnectionString setting on the Configure tab of your mobile service. You might have to reset the password for that login on SQL and also update the connection string just to make sure they are the same.
Another thing that may be a problem is EF migrations. Have you changed your model and enabled migrations? This would all run fine on your local instance and you could add migrations and update database. When you go to deploy though you'd want to enable automatic migrations to make sure the SQL Azure DB also gets the migrations applied. I've seen people have issues with this same error message (ProviderIncompatible) when it was a migrations issue.
To enable auto migrations make sure you go into the configuration.cs file and change the line of code that sets boolean property to "false" by default to "true".
I also had this issue.
My Mobile Service was connecting to my Azure SQL Database called 'Diary'. This was working ok for a few weeks. Then, without any changes from my side , I started getting the error :
Exception=System.Data.SqlClient.SqlException (0x80131904): Cannot open database "master" requested by the login. The login failed. Login failed for user 'HwRkAPcQLyLogin_xxxService'.
I fixed the issue by:
adding the user 'HwRkAPcQLyLogin_xxxService' to my 'Diary' database
assigning db_owner permissions to the 'HwRkAPcQLyLogin_xxxService' user
I used this handy tool to manage the Azure Users:
https://aumc.codeplex.com/
I did not have to change anything in the master database.

Using WCF Service to access SQL Server in Entity Framework -- Why does it seem like it's using Integrated Security?

Quick Background
I received code from a third party (contracted software) that I have to move onto my servers. When I run the code using their connections and service references, everything works well. When I debug locally, everything works well. My problem only occurs when I try to run the application/service(s) after I move them onto my server.
The services (or their respective references) are at the heart of what's causing the issues. I created a test client to try to debug the services, and it's accessing the service, but erroring when it tries to connect to the SQL Server inside the service. The code appears to use the Entity Framework which I am admittedly not familiar with yet.
Errors/Issues
When I use my test client to call a function inside the service reference, it errors out when it tries to connect to my SQL database:
using (ApplicationDefinitionDBEntities appDefDb = new ApplicationDefinitionDBEntities()) //ERROR
Here's the error I receive (domain and server names have been made generic):
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'MYDOMAIN\APPSERVERNAME$'.
I found the app.config that is referenced by the .edmx file (ApplicationDefinitionDB.edmx) and its accompanying files. Here is the connection string (made generic):
<add name="ApplicationDefinitionDBEntities"
connectionString="metadata=res://*/Data.ApplicationDefinitionDB.csdl|res://*/Data.ApplicationDefinitionDB.ssdl|res://*/Data.ApplicationDefinitionDB.msl;
provider=System.Data.SqlClient;
provider connection string="data source=MYDBSERVERNAME;initial catalog=myDBcatalog;
User ID=myUserID;Password=myPassword;integrated security=false;
multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
There is also an old connection string that the third party used which had integrated security set to true and reference SQLExpress, but I commented it out.
Note that I am specifying integrated security to be false (I know it's by default but I wanted to be explicit), and also supplying a username and password to the SQL Server. So why is the error message in the service ref test client saying that it's trying to connect using DOMAIN\APPSERVER$ as though it's using integrated security?
I am using IIS to host my app and SQL Server for database work. I think I have updated and re-generated all Entity Framework stuff for the database reference, but I could be missing something. Can anyone suggest anything that I may be missing to make sure the service reference uses the connection string supplied in it, and NOT the app server domain login? Thanks!
Turns out that connection string conflicted with one above the project level of the service. The project that housed the service uses Silverlight, so I thought the ClientConfig files were the only other configs being used, but there was another one hiding in the project that I published. When I rooted around in that web.config file, I found that there was a connection string with Integrated Security turned on. Once I turned that off it worked fine. That's annoying.

IIS APPPOOL\MyAppPool unable to log in to my SQL Server database

I've got a local WCF web service project that I'm trying to get to access my database. This is my setup:
SQLServer 2008 R2 Express
IIS 7.5
Using IIS APPPOOL\MyAppPool application pool
The AppPool is set to target .Net 4.0 and its identity is set to ApplicationPoolIdentity.
The AppPool user is added in the database and has been assigned dataReader and dataWriter rights. I've tried adding the user to the database both as a "Login" under Security\Logins and as a user under MyDatabase\Security\Users.
Since I'll eventually switch to sql server authentication, I also tried using a real windows user that I assigned reader/writer rights in the database.
I then tried converting the ApplicationPool's identity to NetworkService and added the NT AUTHORITY\NETWORK SERVICE user to the DB aswell but with equal lack of success.
This is the connection string that I'm currently using (With integrated security):
Server=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=true"
As soon as I try to interact with the database in my web service code I get this error:
System.Data.SqlClient.SqlException: Cannot open database "MyDatabase" requested by the login. The login failed. Login failed
for user 'IIS APPPOOL\MyAppPool'.
When using other users than the ApplicationPool then their user names are displayed instead of the IIS APPPOOL one.
Does anyone have any idea what I could've missed?
UPDATE:
With some help from Oded and Tomek I'm now pretty sure that it has to do with the SQL Server. When using SQL Server Authentication I get this error (In the windows event log)
Reason: An attempt to login using SQL authentication failed. Server is configured for Windows authentication only.>
Using Integrated Security (IIS APPPOOL\MyAppPool user) I get this error in the event log
Reason: Failed to open the explicitly specified database.
The server is configured to use "SQL Server and Windows Authentication mode" though which puzzles me. It seems like the second message simply means that the credentials were wrong, which also seems weird since the AppPool user does not have a password. Using the script posted by guptam in post 6 here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=121202 does NOT show my IISAPPPOOL user nor the one created for SQLServer Authentication. The users do exist under both Login and Users and they have the correct rights assigned.
The connection string should be:
"Server=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=SSPI;"
The value for Integrated Security is SSPI, not True.
There is an alternative syntax:
"Server=.\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=True;"
The key here is Trusted_Connection, not Integrated Security.
I suggest taking a look at connectionstrings.com - a good resource for correct connection strings.
Go to your IIS Manager -> ApplicationPool. Right Click your website ApplicationPool and chose Advance Settings. And change Identity to LocalSystem.
Reference
Can you try these steps (some steps of your description are a bit unclear). Let's try to use "sql server authentication"
Create Login Security->Logins, mark "sql server authentication", provide password, untick "user mast change password at next login"
Select "default database" to the one you use
Go to "User Mapping" page and select your database
Use below connection string with user you just configured
connectionString="Data Source=YourDbServerName;Initial Catalog=YourDbName;User ID=YourLogin;Password=YourPass"
I eventually decided to reinstall SSMS and to recreate my database from scratch. It's now up and running as it should. I must've had something fundamentally wrong in some basic setting. Sry for all the confusion and thx for all the help!

Categories