Windows Authentication to Oracle database - c#

I am trying to connect to a Oracle database by using the Windows Identity Token,
it worked yesterday but today it doesn't and I dont know why.
This is my code:
string ssoConnectionString;
var user = CreateSSOConnectionString(connectionStringBuilder, out ssoConnectionString);
oracleConnectionStringBuilder = new OracleConnectionStringBuilder
{
UserID = user.Identity.Name,
ConnectionString = ssoConnectionString
};
private WindowsPrincipal CreateSSOConnectionString(IConnectionStringBuilder connectionStringBuilder, out string ssoConnectionString)
{
var user = new WindowsPrincipal(WindowsIdentity.GetCurrent());
ssoConnectionString = ConfigurationManager.AppSettings["SSOConnectionString"];
ssoConnectionString = string.Format(ssoConnectionString, connectionStringBuilder.Host);
return user;
}
Connection = new Oracle.DataAccess.Client.OracleConnection();
Connection.ConnectionString = oracleConnectionString.ConnectionString;
Connection.Open(); //Fails on this line
The Code doesn't exactly look like this, but it's the essentials.
The SSO ConnectionString is located in app.config and looks like this:
<add key="SSOConnectionString" value="DATA SOURCE={0};User Id=/;" />
Here is a link showing how Oracle them selves explain how to do it: http://docs.oracle.com/cd/E11882_01/win.112/e18754/featConnecting.htm#i1006432
This is the error message I get:
ORA-1017: invalid username/password; logon denied
I have checked with breakpoints and everything looks fine. I've also searched alot around for this error and most people say it's because of password becoming case sensitive in Oracle version 11g, but I'm not providing any password.

What caused this error was actually a mismatch between the Oracle.DataAccess.dll version and the Oracle Client installed on my machine.
So the error is actually not at all related to the code or connection string in the configuration file.
Check your Oracle Client version by writing "sqlplus" in a command window, check that the Oracle.DataAccess.dll version and target .NET framework version matches.

Related

Azure App to Azure Database "Connection Failed" with Entity Framework

I have a C# .Net Web API deployed to an Azure App Service, I also have an Azure SQL Database.
In the API I am using Entity Framework to insert into the database, but I keep getting the error message: "The underlying provider failed on open".
(When running the API locally (in debug mode) connecting to a local database it works fine).
Could this be a permissions/firewall configuration problem with the Azure database, or something else?
I have added my current IP address in the "Azure Set Server Firewall", do I need to add the Azure Web API's IP address to the database firewall settings?
This is my API:
public class ProfileController : ApiController
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
[WebMethod]
[HttpPost]
public HttpResponseMessage PostProfile([FromBody] Profile details)
{
var context = new XXXDBEntities();
var query = from c in context.Users
where c.Email.Equals(details.email, StringComparison.CurrentCultureIgnoreCase)
select c;
var emailFound = query.Count();
if (emailFound != 0)
{
return Request.CreateResponse(HttpStatusCode.OK, "There is already an account associated with this email address");
}
else
{
Guid token = Guid.NewGuid();
Users newRow = new Users();
newRow.Token = token;
newRow.FirstName = details.firstName;
newRow.LastName = details.lastName;
newRow.Email = details.email;
newRow.Password = details.password;
context.Users.Add(newRow);
context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, token);
}
}
This is my connection string:
This is the default format for connection strings in .Net Entity Framework, I have only added username, password and changed the data source and catalog fields. Is this correct?
<add name="XXXDBEntities" connectionString="metadata=res://*/XXXDB.csdl|res://*/XXXDB.ssdl|res://*/XXXDB.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:XXX.database.windows.net,1433;initial catalog=XXXDB;integrated security=True;User ID=XXXXX;Password=XXXXX;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I have checked your connection string, it seems to be right. So I think your issue may be caused by the model of the SQL Azure is changed, but your project does not update it. Here is the same issue I reproduced on my side:
I would suggest you update your model.
do I need to add the Azure Web API's IP address to the database firewall settings?
We can set Allow access to Azure services as ON in SQL Azure firewall settings. So that we need not to add Azure web API's address.
You need to remove Integrated Security=True from the connection string since you are specifying a username and password.

How do you connect from ODP.NET to Oracle (12G+) by proxy user with no password

There seems to be no answer online as to how you can use Oracle Data Provider for .NET (ODP.NET) to connect to Oracle (12G and later) in a very specific scenario:
User is identified externally on a database
User is granted access to another schema (application user) by proxy connect
User has been set up like this:
CREATE USER user_in_question
IDENTIFIED EXTERNALLY
-- etc.
And connect by proxy has been set up like this:
ALTER USER specified_app_user GRANT CONNECT THROUGH user_in_question
The logical approach when creating the ODP.NET OracleConnection string would be something like this (using the user friendly OracleConnectionStringBuilder):
var connBuilder = new OracleConnectionStringBuilder
{
UserID = "/", // External login using the user running the program
ProxyUserId = "specified_app_user",
DataSource = "database",
};
This does not work. Nor does providing blank "Password" or blank "Proxy Password". Nor does removing the UserId.
So how do you connect using ODP.NET in these circumstances?
The answer (which I spend an hour searching for without any luck) is actually really simple, yet not very user friendly:
var connBuilder = new OracleConnectionStringBuilder
{
UserID = "[specified_app_user]",
DataSource = "database",
};
//connBuilder.ToString() output:
//"USER ID=[specified_app_user];DATA SOURCE=database"
This works in .NET 4.5+ on Oracle 12G+, but probably also on earlier platforms of .NET/Oracle/ODP.NET. I did not test it in ASP.NET, but it should work there too.
This way the UserId actually functions just like the ProxyUserId, just enclosed within brackets, just as you would normally log in on the Oracle Database using, say, Toad or SQlPlus.
It might also be possible using this format (but in my case the connection string had to be compatible with the OraOLEDB format so that did not work):
//Without the use of the conn string builder class, just for the fun of it...
var connString = "User Id=specified_app_user;Data Source=database;Proxy User Id=/";
EDITED 2nd March 2017: The line above does not seem to work in certain cases. Added comment about it and here is the code that IS working:
USER ID=[specified_app_user];DATA SOURCE=database
This info does not seem to exist anywhere - else I overlooked it, and in that case PLEASE do correct me.

ASP.NET database connection closes when launching website

I have decided to start programming in ASP.NET MVC using C#
I have been following tutorials and implementing them into my own project.
What happens is that once i click Debug in Chrome/Firefox etc my database connection closes (the red cross appears)! (But when I refresh it manually it has the tick - till that point) I have a feeling it's to do with the connectionString in web.config. I don't like connection strings, to me they seem full of jargon. How many parameters do you REALLY need for a test project?
<connectionStrings>
<add name="PetsDBEntities" connectionString="metadata=res://*/MainDBModel.csdl|res://*/MainDBModel.ssdl|res://*/MainDBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Unfortunately my knowledge of c#/asp.net mvc is VERY limited, hence following a tutorial but I know you guys at SO are really good at what you do.
The database named PetsDBEntities has the following properties.
Data Source: Microsoft SQL Server Database File (SQL Client)
Database File Name: projects/app_data/PetsDB.mdf
If i right click the database and click >Modify Connection and then click test connection I get a "This connection cannot be tested because the specified database file does not exist"
This is where the code breaks. NOTE: The values being submitted are passed through, it just seems that it is unable to connect and add the row to the database.
if (ModelState.IsValid)
{
using( var db = new PetsDBEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var regUser = db.Users.Create();
regUser.Email = user.Email;
regUser.Password = encrpPass;
regUser.PasswordSalt = crypto.Salt;
regUser.UserID = Guid.NewGuid();
db.Users.Add(regUser);
db.SaveChanges(); //--------THIS IS WHERE I GET AN ERROR---------
return RedirectToAction("Index", "Pictures");
}
}
else
{
ModelState.AddModelError("", "Login Data is incorrect!");
}
return View();
Hopefully this is enough information for you guys to spot where the problem is.
Thansk for anyone that can help! Again, I am new and not entirely sure what information is completely needed.
Your issue is likely with the db filename.
attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;
Should be:
attachdbfilename=|DataDirectory|\PetsDB.mdf;
Maybe this can help?
A simple connection string for SQL Server could be Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
You mentioned that when you click on test connection, you are getting an error. Your question title might be misleading, as i can assume that you didn't established the connection at all.
Can you go to "Server Explorer" -> "Data Connections" -> "Add Connection" -> "Microsoft SQL Server Database File", i assume you are using the .mdf file directly instead of connecting to SQL server?
Click on "Test Connection" and if everything goes well, you can retrieve the connectionstring from the properties.

Entity framework connection string enable to connect to DB server

I'm using the entity framework in a winforms application.
When i set scsb.DataSource ="localhost" every thing works fine but when i try to connect to onother DB server i got an exception:
"The underlying provider failed on Open."
public DistributionSSEntities1 Connection()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "192.168.1.100";
scsb.InitialCatalog = "DistributionSS";
scsb.IntegratedSecurity = true;
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata ="res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DistributionSSEntities1 db = new DistributionSSEntities1(builder.ToString());
return db;
}
Has the remote Sql been setup to allow remote connections? Has the remote Sql been allowed access through the windows firewall... there's so many reasons why it wouldn't connect.
You're using Integrated Security - which may work great for a local Sql; but the network user that your WinForm app is running under must have the correct rights to access the remote box.
I'd suggest to start eliminating possibilities do the following:
Check the Sql logs on the target server. That always has the exact reason why an attemp failed - not the watered down version you get through the exception. (eg. C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Log)
Connect to it using a sql username password - not integrated security to make sure it's not that
Firewall
EDIT
It's important to remember that the error messages return to the client regarding login attempt failures are purposefully obscure or without information - to limit an attacker gaining enough information to improve the attack (see the technet article for proof). So checking the Sql Server logs is a necessity - if your login/connection attempt actually made it to the server.
From Article:
To increase security, the error message that is returned to the client
deliberately hides the nature of the authentication error. However, in
the SQL Server error log, a corresponding error contains an error
state that maps to an authentication failure condition. Compare the
error state to the following list to determine the reason for the
login failure.
public DistributionSSEntities Connection()
{
string ConString = "SERVER=192.168.1.100;DATABASE=DistributionSS;UID=sa;PASSWORD=125;";
SqlConnectionStringBuilder SCB= new SqlConnectionStringBuilder(ConString);
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = SCB.ConnectionString;
DistributionSSEntities db = new DistributionSSEntities(builder.ToString());
return db;
}

Cannot retrieve perforce clients

I am trying to develop a C# based build tool using p4api.net apis. I am new to perforce p4api.net. I followed the instructions given in p4api.net library downloaded from their site, but was never successful in running a basic command on perforce. I am attaching piece of code which is supposed to fetch clients from Perforce. Please correct it, if am wrong. The code throws a run time error (unhandled expection) while executing GetClients().
static void Main(string[] args)
{
string uri = "perforce:1666";
string user = "User1";
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
// connect to the server
con.Connect(null);
// run the command against the current repository
IList<Client> changes = rep.GetClients(null);
}
Any useful guide to perforce C# documents/examples would be appreciated.
Thanks,
Madhu
tickets are granted to the user by p4 login. If you login with P4V or another client the ticket should still be valid until expiration unless you explicitly p4 logout. You can create this credential in P4API.NET after you connect and before you run a command:
// connect to the server
con.Connect(null);
string password = "pw";
Credential cred = con.Login(password, null, null);
con.Credential = cred;
Are you sure that the exception is coming from GetClients? I ran your code successfully, but when I changed uri to a non-existent server:port I get the unhandled exception at con.Connect(null).
Confirm that you do have access to a perforce:1666 server with User1 and that User1 does not require a password on that server.

Categories