Using Audit.NET SqlDataProvider with Azure SQL and Managed Identity - .net-core

We are using the Audit.NET SqlServer Data Provider to store Audit logs in our Microsoft SQL Server. We are currently in the progress of migrating to the use of Azure SQL with Managed Identity to access the database. We haven't been able to get Audit.NET working with Azure SQL and the use of Managed Identity to connect to said database. The documentation doesn't provide any information on whether this functionality is supported or not.
We have managed to do this for our own database connections using Entity Framework Core by adding an Access Token to the SQL connection used by the Context like so:
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.AccessToken = new AzureServiceTokenProvider()
.GetAccessTokenAsync("https://database.windows.net/")
.Result;
This works perfectly fine. The issue we are running into is that we want to achieve the same with the Audit.NET Sql Data Provider. Due to the AuditContext being used by the SqlDataProvider being internal we are unable to pass an Access Token to the SqlConnection used.
The only solution we've come up with is writing our own Data Provider that is virtually the same as the SqlDataProvider, the only difference being that the Context used will set an Access Token on the SqlConnection. Is this the only viable solution here or does Audit.NET offer some other way to get it working with Azure SQL and Managed Identity?

I think the best way could be exposing an optional setting to provide the DbContextOptions where you can set an Interceptor like the one from here to set the AccessToken for the connection.
So you could initialize your configuration like this:
Audit.Core.Configuration.Setup()
.UseSqlServer(sql => sql
.ConnectionString("connection string")
.DbContextOptions(new DbContextOptionsBuilder()
.AddInterceptors(new AzureAuthenticationInterceptor(new AzureServiceTokenProvider()))
.Options));
or
Audit.Core.Configuration.Setup()
.UseSqlServer(sql => sql
.DbContextOptions(new DbContextOptionsBuilder()
.UseSqlServer("connection string")
.AddInterceptors(new AzureAuthenticationInterceptor(new AzureServiceTokenProvider()))
.Options));
UPDATE
The new DbContextOptions settings was added on version 16.2.1

Related

SSAS Error The MyCube either does not exist or has not been processed when attempting to query through ASP.NET

I have a cube, which has been processed, works from the BID environment, and I can run my MDX query in both SSEM, and the BID env. I've created a role that contains the proper accounts/permissions, processed, and deployed the cube, re-processed it in SSEM, etc. Now I'm trying to connect, and extract the data using ASP.NET 4.0, but I'm getting this error:
The MyCube either does not exist or has not been processed
Here's my code:
String connectionString = "Provider=MSOLAP.3; Data Source=myhost;Initial Catalog=myCatalog; User ID=myaccount; Password=myamazinglysecurepassword;";
String mdxSQL = " my MDX, which was taken directly from BID env. cube in design mode";
AdomdConnection connection = new AdomdConnection(connectionString);
connection.Open();
AdomdCommand cmd = new AdomdCommand(mdxSQL, connection);
CellSet cst = cmd.ExecuteCellSet();
...etc
Note: we are not using MSMDPUMP.dll to connect, we'd like to avoid that.
Any Ideas?
A couple things to consider. How are users authenticating to your web app? What account is your application pool running as?
If you're using Integrated Windows in ASP.NET you may be getting a double-hop issue if IIS and SSAS on different servers. This would require you to set up Kerberos and trusted delegation SPN's between your application and the OLAP service.
See (SSAS and IIS):
http://msdn.microsoft.com/en-us/library/dn194199.aspx
http://technet.microsoft.com/en-us/library/dd632778.aspx
Otherwise there may be an issue with the account your application pool is running under. I see in your connection string you have a specific account - so I presume you are trying to connect as one account rather than delegating user credentials to OLAP. The process running w3wp.exe is the identity which will attempt to connect to SSAS. If your application pool is not runnning as a domain account is may not be able to authenticate to SSAS.

How to construct ConnectionStrings

Could you explain me how to construct correct ConnectionStrings? I mean that one you can find in web.config file in MVC project. I understand that if you want to add a new connection string you have to write <add ... /> XML tag with parameters such as name, connectionString (it is the most interesting parameter for me) and providerName (perhaps some else?). What each parameter does and means? How to construct connectionString parameter? Where is the db engine indicated?
The questions above are only examples. I care about collecting the most amount of information about constructing ConnectionStrings.
Starting from NET 2.0 you have at your disposal a class named SqlConnectionStringBuilder
Its purpose is to help building dynamically the connection string. But the various properties available explain in great detail the functionality underlying to each possible setting
The SqlConnectionStringBuilder class is derived by a base class named DbConnectionStringBuilder and this allows all the ADO.NET provider to implement their own version of this class. In the link provided there are the references relative to other ADO.NET providers
If you are trying to construct entity framework connection string just use as follows.It will help you..
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
UPDATED:
The easiest way to get the connection string is using the Server explorer window in Visual Studio (View-->Server Explorer menu) and connect to the server from that window. Then you can see the connection string in the properties of the connected server (F4 with your connection selected).
If you create the database in SQL Server Management Studio, that database will be created in a server instance, so that, to deploy your application you'll have to make a backup of the database and deploy it in the deployment SQL Server. Alternatively, you can use a data file using SQL Server Express (localDB in SQL Server 2012), that will be easily distributed with your app.
I.e. if it's an ASP.NET app, there's an App_Datafolder. If you right click it you can add a new element, which can be a SQL Server Database. This file will be on that folder, will work with SQL Express, and will be easy to deploy. You need SQL Express installed on your machine.

The underlying provider failed on open entity framework

I am unsing entity framework in my web application. Earlier everything was working fine. But then I deleted database from Sql Server. After that whenever I run the application, I get the following exception :
The underlying provider failed on open entity framework
Isn't it true that if we delete the database from Sql Server and again run the application, database is again created?
Can you show some details about connection string. I basically want to check the authentication you are using.
Demo for setting a typical authentication : http://msdn.microsoft.com/en-us/library/ff649314.aspx
Another possibility can be with connection pooling. Try explicitly closing the connection(if there are any open connections)
db.Database.Connection.Close();
Entity framework will recreate your database on application start assuming the following:
You have permission to create databases in SQL
A connection string is specified correctly (if it was working before this should be fine)
You are using CodeFirst or ModelFirst strategies for databases (ie if you generated an EDMX off an existing database it wont recreate it for you)
I had a similar error and it was due to the connection problem.
Usually you need to open your *.EDPS file under your entity (EDML) and check your connection string and make sure it has got a correct setting especially your Default Oracle home.

Cannot open database 'dbname' requested by the login. The login failed

Firstly, I know that there are a lot of similar topics, but none seem to solve my problem.
I have inherited a project where the front-end is built in ASP.NET and the CMS is built in classic ASP. I'm in the process of setting up a local development environment where I've copied the database from the live server and am configuring the website to connect to my new local DB.
The ASP.NET part is connecting with the connection string Data Source=.\\SQLEXPRESS; Database=DBNAME; Trusted_Connection=True; but I had to mess about with Application Pools and Permissions.
I'm having a problem with getting the classic ASP part of the website to connect to the SQL database. The error I am recieving is:
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "DBNAME" requested by the login. The login failed.
/cms/connections/Conn.asp, line 18
The code in that file is:
12. Dim Conn_STRING, URL, mailHost
13. Conn_STRING = "Driver={SQL Server}; Server=.\SQLEXPRESS; Database=DBNAME; Trusted_Connection=True;"
15. Dim conn
16. set conn = Server.CreateObject("ADODB.Connection")
17. conn.ConnectionString = Conn_STRING
18. conn.Open
I know it's a permission problem or some sort, but I can't get to the bottom of it. I'll appreciate any help at all :)
hmmmm, well, the asp.net part is using SQLExpress, connected via an attached file. DBNAME in the first example is going to refer to a db file name in the actual asp.net project. It's been quite a long time since I last used classic ASP, but I'd be STUNNED if it supports this. You need to attach the db file to an actual sql server and use it that way.
server=mycomputername\sqlexpress; database=DBNAME; user id=username; password=password
You'll need to open your database in sql express mngmt studio
http://www.microsoft.com/download/en/details.aspx?id=7593
Go into your security settings for that user and set the default database to "dbname" (whatver your real dbname is of course)
Ensure your app pool is set to run under the user that has permissions to that database. It may just be easier to enable mixed mode authentication and create a sql user to connect to the database rather than messing around with windows authentication on an app pool.
You wil lof course need to change your connection string then to support the sql authentication if you go that route.
http://msdn.microsoft.com/en-us/library/ms143705%28v=sql.90%29.aspx

How can I create a database on my server from the web?

I have an admin account for my website where I add new clients. When a new client is added, they get an account and their own database.
The problem is I can't create new databases on my server from my admin account. When running it locally, I can add a database locally. But, when I try adding to the server running my website off the server, I get
CREATE DATABASE permission denied in database 'master'.
I've been able to add the database (locally) a few ways. This is one of the simpler working versions:
tmpConn.ConnectionString = "Data Source=.\\SQLEXPRESS; DATABASE = master;Integrated Security=True;";
sqlCreateDBQuery = " CREATE DATABASE " + dbname;
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{}
I suspect that whatever account you're using to connect to Sql Server doesn't have permissions to CREATE DATABASE. You're probably using Integrated Security, which would use Network Service/ASP.NET to connect to MSSQL. You need to create a new connection string that uses Sql Authentication with sa (or another sysadmin) credentials.
Oh - and this would work locally because you're running it under Visual Studio's WebDev.exe which is run with your local user account - which is probably set up as a sysadmin in MSSQL.
You should contact your service provider. (Or the maintainer of the server).
You need create database and create database user permissions. Your service provider should be able to facilitate this.
Something else no one has suggested is what kind of validation you are doing on the dbname value. Are you sure there are no spaces in it? That it's not a reserved word? That it doesn't contain malicious code? At very least you should encase it in brackets:
sqlCreateDBQuery = String.Format(" CREATE DATABASE [{0}]", dbname);
I really hope you aren't allowing the user to type this name directly into a textbox somewhere. Even if you use property security on the initial input and this is pulled back from a common "clients" db of some kind, you might be setting yourself up for a 2nd order Sql Injection vulnerability.
After you've addressed that, we can look at the error message here. In this case, the problem is that your web user does not have appropriate CREATE permissions. You need to correct that and it should allow you to proceed. You probably want to reserve a special account for this that you switch to just at this time, so your application doesn't normally run in a context that would allow this kind of action.
Check the permissions for MySQL: Does your admin account have different settings for a local connection versus any host?

Resources