ASP.NET Core Rest API Saving Failed saying no access to another database - rest

My ASP.NET Core Rest API is returning a 500 Internal Server Error on post method while adding a new customer. I am able to get data from my development database, but myDbContext.SaveChanges(); failed saying my development user doesn't have access to the main database, but my connection string refers to my development database only.
My database name : MyappDbDev
My database user : AppUserDev
Error:
The server principal "AppUserDev" is not able to access the database "MyappDbDev" under the current security context
I have another database in production with following credentials:
Database name : MyappDb
Database user : AppUser

I didn't find any useful suggestions after researching for days, at last I found that I had a trigger for the table that I am adding new record.
which the trigger had insert command to old database.
It was a silly mistake , but I hope this may help someone someday.

Related

Managed Identity Sql Auth with EF Core - Login failed for user '<token-identified principal>'

I have a dotnet 5 (isolated) Azure Function app that needs to access an Azure Sql Server database via EF Core 5. I would like to use the managed identity of the function app when making the sql server requests.
What I tried
I followed the instructions here.
I created a new AD account called "smsrouterdb" and made this the Azure Sql Admin.
The name of my function app is "func-smsrouter-msdn-01". So after logging into the DB via SSMS as "smsrouterdb", I created a contained user as below:
CREATE USER [func-smsrouter-msdn-01] FROM EXTERNAL PROVIDER
ALTER ROLE db_datawriter ADD MEMBER [func-smsrouter-msdn-01]
ALTER ROLE db_datareader ADD MEMBER [func-smsrouter-msdn-01]
I then triggered my function app via an http request.
What happened
I got the following error from the function app:
One or more errors occurred. (Invalid value for key 'authentication'.) ---> System.ArgumentException: Invalid value for key 'authentication'. at Microsoft.Data.Common.DbConnectionStringBuilderUtil.ConvertToAuthenticationType(String keyword, Object value)
I realised that this was because an old version of the nuget package Microsoft.Data.SqlClient was being referenced. So, I explicitly added a reference to v3.0.0.
I then got the following error
Login failed for user '<token-identified principal>'
However, if I change the connection string's authentication property to "Active Directory Interactive" and promote the object id of the managed identity for the function app to be Sql Admin using the following command:
az sql server ad-admin create --resource-group <tg name> --server-name <server name> --display-name MSIAzureAdmin --object-id "id of managed identity here"
then the rows are written correctly. My concern is that the managed identity should not need to be a sql admin.
Config
The nuget packages of the project containing the dbcontext are:
"Microsoft.Azure.Services.AppAuthentication" Version="1.6.1"
"Microsoft.EntityFrameworkCore" Version="5.0.6"
"Microsoft.EntityFrameworkCore.Design" Version="5.0.6"
"Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.6"
"WindowsAzure.Storage" Version="9.3.3" />
From the main Azure Function project, I have references to the following nuget packages:
Microsoft.Data.SqlClient 3.0.0
Serilog.Sinks.MSSqlServer 5.6.0
The only code in my db context is:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
SqlConnection connection = new SqlConnection();
logger.LogInformation($"SqlSvrConString=[{sharedConfig[ConfigConstants.SqlSvrConnString]}]");
connection.ConnectionString = sharedConfig[ConfigConstants.SqlSvrConnString];
optionsBuilder.UseSqlServer(connection);
}
My connection string is:
Server=servernamehere.database.windows.net;Initial
Catalog=dbnamehere;Authentication=Active Directory Managed Identity;
Can anyone explain why this fails unless the managed identity is made sql admin?
I think the root cause of the problem was that when I'd issued the command: CREATE USER [function name here] FROM EXTERNAL PROVIDER, although the function name was spelled correctly, the case was incorrect.
One easy way to work around these kind of errors is to use the guid of the functions identity instead of the name. This works as well.
CREATE USER [abcdef-1234-5678-ghijkl] FROM EXTERNAL PROVIDER

Azure database works on localhost, but not when used with azure service app

So I've been trying to publish my first project to azure. I've got everything set-up, a service app and a sql database.
My initial page loads properly(It's the standard view for a .net core web application).
The first thing I need to do is register a new user. Whenever I try through my azure app (myapp.azurewebsites.net) it fails and the logs says it's db related.
However I try the same thing by running the application on my machine in production environment, again connected to the azure sql server and everything works perfectly. I can register users, I can create posts, I can edit them. The allow access to azure services option is turned on. This error is from the eventlogs. I have not included the stacktrace.
Category: Microsoft.EntityFrameworkCore.Query EventId: 10100 RequestId: 800001be-0000-ba00-b63f-
84710c7967bb RequestPath: /Identity/Account/Register SpanId: |1e5a93ae-43f424904f38ea9f. TraceId:
1e5a93ae-43f424904f38ea9f ParentId: ActionId: c3430236-e61c-4785-a3c3-4f60ba115b6e ActionName:
/Account/Register An exception occurred while iterating over the results of a query for context type
'MyApp.Data.ApplicationDbContext'. Microsoft.Data.SqlClient.SqlException (0x80131904): Server
name cannot be determined. It must appear as the first segment of the server's dns name
(servername.database.windows.net). Some libraries do not send the server name, in which case the
server name must be included as part of the user name (username#servername). In addition, if both
formats are used, the server names must match.
Those are the different ways I tried to add the connection string to the appsettings.json file. (Server name, catalog, user and password have been replaced, they are written correctly in the appsettings file)
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user#server;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;
Alright so after a day and a half, I finally managed to fix it. The solution is rather simple and it is most likely my newbie mistake, that caused so much trouble.
I was following a tutorial for setting up the application and database connection after that. In the tutorial, the connection string that was being used, was the default one, found in the "myApp -> Configuration -> Connection strings", the format was:
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;
This one was working in the guide, but not for me. So what I did, was go to my "sqldb -> connection strings" and copied the one provided there. I then went back to the app configuration and added it as a new configuration string using SqlServer as the Type.
This string was in the format:
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
After that, the app started working properly.

Tables not created with Entity Framework on Azure

I am using Entity Framework using Code First and the Fluent API.
When developing on my local machine, the database and tables are created as expected and everything works fine.
When deploying to my Azure web role the database is created, but the tables are never created. If I try a HTTP request touching DbContext, the request times out and finally my web role only returns "Service Unavailable".
The model is large, but not extremely so (43 tables are created on my dev machine).
What can be wrong here? Here is my Azure SQL connection string, where you can see that I set the timeout quite high:
<add name="MyConnectionString" connectionString="Server=tcp:myserveronazure.database.windows.net,1433;Database=MyDatabase;User ID=MyUser#myserveronazure;Password=thepassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=120;PersitSecurityInfo=true;" providerName="System.Data.SqlClient" />
EDIT: After RDP:ing into the Azure VM, I see in the Event Log that w3wp.exe (the IIS worker process, if I'm not mistaken) crashes. The log doesn't list any error message.
Enityframework have three Database Initializer by default CreateDatabaseIfNotExists,DropCreateDatabaseWhenModelChanges and DropCreateDatabaseAlways that are executed when you hit the context for the first time, if you are using migrations (i think is the case) you must use the MigrateDatabaseToLatestVersion initializer to work in the application deployment. Hope it works!

Using SQL Server CE 4.0 with Entity Framework on Windows Azure

I am using SQL Server CE 4.0 with WebApi on Windows Azure Websites. I have been successfully able to deploy SQL Server CE. The weird problem I am facing is that my site is able to log me in using the same DB but I am not able to use any of the controllers to fetch the data.
I am using same connection string for both. The only difference is that for logging in I am using WebSecurity as I have enabled OAuth on the site.
Can someone throw some light on how to debug and fix this issue? The error I am getting for the calls is
Format of the initialization string does not conform to specification
starting at index 0.
However the same string works for authentication, change password, adding OAuth connections etc.
Thanks in advance
I connected to the site using FTP. I was not giving the site name as domain name and it was denying me access earlier. On connecting, I got hold of the Web.config file and I found something interesting. While publishing the site, the web.config was modified to add another connectionstring with the name of context_DatabasePublish.
This string had following details connectionString="ContextName_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient"
Also there was a new section called context added to the entityframework section of the config file with all the details for the context to use but again pointing to same connection string. The provider it is using is sql and not sqlce. I believe that is the reason it was failing.
I uploaded my normal config file and the site started working. I need to explore more on to why and how the new connection string got added. I will post the details in comments.

Authentication in couchdb for ios

I am working on the couchdb . I am using the replication between remote server and local server . I want to user the user name and password on the header field in the encrypted format in the couch cocoa frame work .
i am getting this error Replicator: couldn't write document _design/sample, revision 1-53ef232135548f38c879df297b886c99, to target database iphone. Error: unauthorized, reason: You are not a db or server admin..
Replicator, request GET to "http:*///iphone/_changes?feed=continuous&heartbeat=10000&style=all_docs&since=0" failed due to error timeout
i tried to add the set credential methods , but i need to use int he encrypted format plz help me
Thanks&regards
It looks like you already asked this question (three times) in the mobile-couchbase Google group. For completeness I'll just link to the thread there, with the reply I already posted this morning:
https://groups.google.com/forum/?fromgroups#!topic/mobile-couchbase/AVpUCseNnIg