External Control of System or Configuration Setting (CWE ID 15) - c#

We had security threat issue when scanning applications in Veracode. Got "External Control of System or Configuration Setting (CWE ID 15)".
Scan reported for using (var connection = new SqlConnection(connectionString))
we are checking whether "SQLConnectionExists" by passing connection string,
string sqlConnString = SqlHelper.GetSQLConnectionString(input.ServerName, dbName, isWinAuth, input.UserName, input.Password);
if (!DBUtil.CheckSQLConnectionExists(sqlConnString))
{
_ValidationMessage += "Database Unreachable \n";
isValid = false;
}
public static bool CheckSQLConnectionExists(string connectionString)
{
bool isExist = false;
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
connection.Close();
isExist = true;
}
}
catch (Exception ex)
{
Logger.Instance.Log(LogLevel.EXCEPTION, "CheckSQLConnectionExists Exception : " + ex.Message);
}
return isExist;
}
public static string GetSQLConnectionString(string servername, string db, bool isWinAuth, string username, string password)
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = servername;
builder["Initial Catalog"] = db;
if (isWinAuth)
{
builder["Integrated Security"] = "SSPI";
builder["Trusted_Connection"] = "Yes";
}
else
{
builder["Persist Security Info"] = false;
builder["User ID"] = username;
builder["Password"] = password;
}
return builder.ConnectionString;
}
In this line using (var connection = new SqlConnection(connectionString)) we got error in security scan. Could you please some one provide suggestions to resolve this Veracode error.

Veracode detects input.ServerName, input.UserName and input.Password to be user-controlled which is a risk.
Ensure validation is implemented - if possible, compare against a whitelist or known predefined server names. Also, check if the entered (injected) Min Pool Size is larger than expected. Use framework classes such as the one that you used SqlConnectionStringBuilder
Propose this check as a mitigation afterwards.

Related

How to authenticate in LDAP in C#?

I am new to LDAP related coding and today I am asked to develop a code to check the users authentication against LDAP.
The tutorials I have found online are so simple but our company's Directory is so complicated that I don't know how to write a code for that. Here is the info of the LDAP . I have changed the company name to hide the name.
string domain = "ou=People,dc=my,dc=com";
string LDAP_Path= "dc01.my.com;
string LDAPconnect= "LDAP://dc01.my.com/";
Here is a code I have developed but it gives me error when run " LdapResult = LdapSearcher.FindOne();":
string domain = "ou=People,dc=my,dc=com";
string password = "";
string userName = "";
// define your connection
LdapConnection ldapConnection = new LdapConnection(LDAP_Path);
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(userName, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
Response.Write( "connect ldap success");
}
}
catch (LdapException ldapException)
{
Response.Write(ldapException + " <p>Ad connect failed</p>");
//Authentication failed, exception will dictate why
}
string strTmp0 = LDAPconnect + domain;
string user = "memberId";
string pwd = "memberPwd";
System.DirectoryServices.DirectoryEntry LdapEntry = new System.DirectoryServices.DirectoryEntry(strTmp0, "cn=" + user, pwd, AuthenticationTypes.None);
DirectorySearcher LdapSearcher = new DirectorySearcher(LdapEntry);
LdapSearcher.Filter = "(cn=" + user + ")";
string value = string.Empty;
SearchResult LdapResult=null;
try
{
LdapResult = LdapSearcher.FindOne();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
// .............get Error msg : username an password uncorrect
}
if ((LdapResult != null))
{
Response.Write("ldapresult not null");
}
Could anybody help plz?
In ldap connection setting , OP should use own configuration.
// Ldap connection setting. this should setup according to organization ldap configuration
int portnumber = 12345;
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("ldap.testxxxx.com", portnumber));
ldapConnection.AuthType = AuthType.Anonymous;
ldapConnection.Bind();
SearchRequest Srchrequest = null;
SearchResponse SrchResponse = null;
SearchResultEntryCollection SearchCollection = null;
Hashtable UserDetails = new Hashtable();
Srchrequest = new SearchRequest("distniguishged name e.g. o=testxxx.com", string.Format(CultureInfo.InvariantCulture, "preferredmail=test#testxxxx.com"), System.DirectoryServices.Protocols.SearchScope.Subtree);
SrchResponse = (SearchResponse)ldapConnection.SendRequest(Srchrequest);
SearchCollection = SrchResponse.Entries;
foreach (SearchResultEntry entry in SearchCollection)
{
foreach (DictionaryEntry att in entry.Attributes)
{
if (((DirectoryAttribute)(att.Value)).Count > 0)
{
UserDetails.Add(att.Key.ToString(), ((DirectoryAttribute)(att.Value))[0].ToString());
}
else
{
UserDetails.Add(att.Key.ToString(), string.Empty);
}
}
}
if (UserDetails.Count > 1)
{
Console.WriteLine("User exists");
}
else
{
Console.WriteLine("User does not exist");
}
You can use the DirectoryInfo conrstructor that has user and password arguments. That way, you don't need to do a query to the LDAP, you can simplify your code.
string username = "frederic";
string password = "myFanciPassword99";
string domain = "ou=People,dc=my,dc=com";
string LDAPconnect= "LDAP://dc01.my.com/";
string connectionString = LDAPconnect + domain;
bool userValid = false;
// Note: DirectoryEntry(domain, username, password) would also work
DirectoryEntry entry = new DirectoryEntry(connectionString, username, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
userValid = true;
}
catch (Exception ex)
{
}

Creating LDAP Connection on .NET

I am trying to Create LDAP Cnnection using c# .
I found this server which gives LDAP Server to Test
http://www.forumsys.com/en/tutorials/integration-how-to/ldap/online-ldap-test-server/
I have googled many post and Tried to create a consolidated Code
string domain = "ldap://ldap.forumsys.com/ou=mathematicians";
string username = "cn=read-only-admin,dc=example,dc=com";
string password = "password";
string LdapPath = "Ldap://ldap.forumsys.com:389/ou=scientists,dc=example,dc=com";
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
// Update the new path to the user in the directory
LdapPath = result.Path;
string _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user." + ex.Message);
}
This code is not connecting it is giving unexpected error ..
I also Tried some other Credentials , But they are not helping either ...
AUTH_LDAP_SERVER_URI = “ldap://ldap.forumsys.com”
AUTH_LDAP_BIND_DN = “cn=read-only-admin,dc=example,dc=com”
AUTH_LDAP_BIND_PASSWORD = “password”
AUTH_LDAP_USER_SEARCH = LDAPSearch(“ou=mathematicians,dc=example,dc=com”,
ldap.SCOPE_SUBTREE, “(uid=%(user)s)”)
--------------------
$config[‘LDAP’][‘server’] = ‘ldap://ldap.forumsys.com';
$config[‘LDAP’][‘port’] = ‘389’;
$config[‘LDAP’][‘user’] = ‘cn=read-only-admin,dc=example,dc=com';
$config[‘LDAP’][‘password’] = ‘password';
-------------------------
$config[‘LDAP’][‘server’] = ‘ldap://ldap.forumsys.com/ou=mathematicians';
$config[‘LDAP’][‘port’] = ‘389’;
$config[‘LDAP’][‘user’] = ‘gauss';
$config[‘LDAP’][‘password’] = ‘password';
--------------------------
OpenDSObject/GetObject functions, but don’t see a way to run a query with the ASDI objects.
Set LDAP = GetObject(“LDAP:”)
Set root = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389″, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
Set ou = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389/ou=mathematicians,dc=example,dc=com””, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
Set user = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389/uid=riemann,dc=example,dc=com”, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
I need some suggestion what I am missing . any resource will be helpful
I had a somewhat similar issue with this server and google sent me here.
One issue I see is that case sensitive issue in LDAP path. Also we should specify the AuthenticationType as well.
Please check following code block which should work.
string ldapServer = "LDAP://ldap.forumsys.com:389/ou=scientists,dc=example,dc=com";
string userName = "cn=read-only-admin,dc=example,dc=com";
string password = "password";
var dirctoryEntry = new DirectoryEntry(ldapServer, userName, password, AuthenticationTypes.ServerBind);
try {
object nativeObject = dirctoryEntry.NativeObject;
//Rest of the logic
} catch (Exception ex) {
//Handle error
}
Trying using PrincipalContext to connect to the LDAP server. Here is a good how-to article I referenced when I was getting started: http://ianatkinson.net/computing/adcsharp.htm
ctx = new PrincipalContext(
ContextType.Domain,
"contoso.local",
"OU=Security Groups,OU=Contoso Inc,DC=contoso,DC=local",
"contoso\sysadmin",
"P#ssword1");
Namespace - using System.DirectoryServices.Protocols;
methode -
private bool ldapValidateUser(string fullname, string password)
{
try
{
LdapDirectoryIdentifier ldap = new LdapDirectoryIdentifier("Directory Host", true, false);
LdapConnection connection = new LdapConnection(ldap);
connection.AuthType = AuthType.Basic;
string ldapuser = "cn=" + fullname + ",ou=Org Unit,dc=Value,dc=local";
connection.Credential = new System.Net.NetworkCredential(ldapuser, password);
connection.Bind();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}

Error 0x80005000 with LdapConnection and LDAPS

Before I start, I've already visited Unknown Error (0x80005000) with LDAPS Connection and changed my code and while it did solve the problem it seems that it has mysteriously come back.
Here's the good stuff:
public static bool Authenticate(string username, string password, string domain)
{
bool authentic = false;
try
{
LdapConnection con = new LdapConnection(
new LdapDirectoryIdentifier(Host, Port));
if (IsSSL)
{
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.VerifyServerCertificate = ServerCallback;
}
con.Credential = new NetworkCredential(username, password);
con.AuthType = AuthType.Basic;
con.Bind();
authentic = true;
}
catch (LdapException)
{
return false;
}
catch (DirectoryServicesCOMException)
{ }
return authentic;
}
public static bool IsSSL
{
get
{
return ConnectionString.ToLower().Contains("ldaps");
}
}
public static string ConnectionString
{
get
{
if (string.IsNullOrEmpty(_connectionString))
_connectionString = CompleteConfiguration.GetLDAPConnectionString();
return _connectionString;
}
set { _connectionString = value; }
}
public static int Port
{
get
{
var x = new Uri(ConnectionString);
int port = 0;
if (x.Port != -1)
{
port = x.Port;
}
else
{
port = x.OriginalString.ToLower().Contains("ldaps")
? 636
: 389;
}
return port;
}
}
public static string Host
{
get
{
var x = new Uri(ConnectionString);
return x.Host;
}
}
private static bool ServerCallback(LdapConnection connection, X509Certificate certificate)
{
return true;
}
Here's the bad stuff:
When I attempt to authenticate to the application I get the following error, to be precise this is triggered by the con.Bind() line:
[COMException (0x80005000): Unknown error (0x80005000)]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +378094
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_NativeObject() +31
Complete.Authentication.GCAuthentication.Authenticate(String username, String password, String domain) in c:\Builds\6\Idealink.Open.Pancanal\Panama Canal\Sources\Idealink.Open\Complete.Authentication\GCAuthentication.cs:27
Complete.Authentication.AuthenticationFactory.ValidateUserLdap(String username, String password, String domain, Boolean isValid, String usernameWithDomain) in c:\Builds\6\Idealink.Open.Pancanal\Panama Canal\Sources\Idealink.Open\Complete.Authentication\AuthenticationFactory.cs:93
It is quite confusing as it seems that some user accounts work and others don't. However when I place the above code in an isolated test environment it does succeed each and every time regardless of which account I use. When I place it back on the Windows 2008 R2 Server with ASP.NET and IIS it fails as stated above. The failures are consistent though - accounts consistently fail or succeed, from that perspective there is no randomness.
The LDAP Server must be accessed using LDAPS and NOT LDAP which is why we cannot use the DirectoryEntry object - the LDAP server is controlled by a client and therefore cannot be reconfigured or altered in any way. We simply want to capture username/password on a web form and then use BIND on the LDAP server to check credentials.
We are using .NET 3.5 and cannot upgrade at this time so I respectfully ask that if your main suggestion and arguments are to upgrade than please hold off on your contribution.
Thanks, hope you can help
Would something like this work for you..?
const string Domain = "ServerAddress:389";
const string constrParts = #"OU=Users,DC=domain,DC=com";
const string Username = #"karell";
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, Domain, constrParts);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
Here is a really good site for great references and examples
DirectoryServices DirectoryEntry
for Connection over SSL you could do something like the following
const int ldapInvalidCredentialsError = 0x31;
const string server = "your_domain.com:636";
const string domain = "your_domain.com";
try
{
using (var ldapSSLConn = new LdapConnection(server))
{
var networkCredential = new NetworkCredential(username, password, domain);
ldapSSLConn.SessionOptions.SecureSocketLayer = true;
ldapSSLConn.AuthType = AuthType.Negotiate;
ldapSSLConn.Bind(networkCredential);
}
// If the bind succeeds, the credentials are valid
return true;
}
catch (LdapException ldapEx)
{
// Invalid credentials a specific error code
if (ldapEx.ErrorCode.Equals(ldapInvalidCredentialsError))
{
return false;
}
throw;
}
MSDN list of Invalid LDAP Error Codes

Passing ConnectionString from SqlConnectionSringBuilder to ConnectionManager

I want to get a ConnectionString from an instance of SqlConnectionStringBuilder as a String.
This seems simple, and should be as easy as this:
String conString = builder.ConnectionString;
However the String that SqlConnectionStringBuilder gives up doesn't include the Password field/value. I'm guessing this is some sort of security feature, is there a way to force Password to be included in the String?
Looking at this further I'm thinking this may have something to do with ConnectionManager. What I am trying to do is modify the ConnectionString for a Package, changing the Initial Catalog.
Below is my code, the point that builder's connection string is passed back into connectionManager's the Password is lost...
public void DataTransfer(String sourceConnection, String destConnection, String pkgLocation)
{
Package pkg;
Application app;
DTSExecResult pkgResults;
try
{
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
foreach (ConnectionManager connectionManager in pkg.Connections)
{
SqlConnectionStringBuilder builder;
switch (connectionManager.Name)
{
case "SourceConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
connectionManager.ConnectionString = builder.ConnectionString.ToString();
connectionManager.ConnectionString += ";Provider=SQLNCLI;Auto Translate=false;";
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
case "DestinationConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
connectionManager.ConnectionString = builder.ConnectionString.ToString();
connectionManager.ConnectionString += ";Provider=SQLNCLI;Auto Translate=false;";
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
}
}
pkgResults = pkg.Execute();
}
catch (Exception e)
{
throw;
}
Console.WriteLine(pkgResults.ToString());
}
Set PersistSecurityInfo to True before setting other properties in the SqlConnectionStringBuilder : D
I need to rename this a little maybe, as the question is different now, but here is my solution:
The first part of this question was answered correctly by #madd0. The ConnectionString does contain the Password field.
The second part was solved with formatting code is below:
public void DataTransfer(String sourceConnection, String destConnection, String pkgLocation)
{
Package pkg;
Application app;
DTSExecResult pkgResults;
try
{
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
foreach (ConnectionManager connectionManager in pkg.Connections)
{
SqlConnectionStringBuilder builder;
switch (connectionManager.Name)
{
case "SourceConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
var sourceCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
//Added spaces to retain password!!!
sourceCon = sourceCon.Replace(";", "; ");
connectionManager.ConnectionString = sourceCon;
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
case "DestinationConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
var destCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
//Added spaces to retain password!!!
destCon = destCon.Replace(";", "; ");
connectionManager.ConnectionString = destCon;
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
}
}
pkgResults = pkg.Execute();
}
catch (Exception e)
{
throw;
}
Console.WriteLine(pkgResults.ToString());
}
I played about with the ConnectionStrings and noticed after a while that the original String had spaces between each property.
Running 2 tests I found that without spaces the Password was lost...
connectionManager.ConnectionString = destCon;
Test 1: No Spaces:
When destCon = Data Source=xxx.xxx.xxx.xxx;Initial Catalog=StagingArea;User ID=*****;Password=*****;Provider=SQLNCLI;Auto Translate=false;
Then connectionManager.ConnectionString = Data Source=xxx.xxx.xxx.xxx;User ID=*****;Initial Catalog=StagingArea;Provider=SQLNCLI;Auto Translate=false;
Test 2: Spaces:
When destCon = Data Source=xxx.xxx.xxx.xxx; Initial Catalog=StagingArea; User ID=*****; Password=*****; Provider=SQLNCLI; Auto Translate=false;
Then connectionManager.ConnectionString = Data Source=xxx.xxx.xxx.xxx; Initial Catalog=StagingArea; User ID=*****; Password=*****; Provider=SQLNCLI; Auto Translate=false;
No idea why this happens, but without spaces the ordering is adjusted and the Password field is lost.

Get user and password from ConnectionStringSettings

How can I get the user and password from such a connectionString in the app.config with a .NET function?
Of course I could read that string and get the value after the ID= and Password=.
<connectionStrings>
<add name="MyConString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUsername Password=MyPassword;Connect providerName="System.Data.SqlClient"/>
</connectionStrings>
use the ConnectionBuilderClass
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder("Your connection string");
string password = builder.Password;
together with the
string connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
to achieve this.
If you need a more generic approach for parsing the connection string (one that doesn't deal with the specifics of one database provider) you can also use
System.Data.Common.DbConnectionStringBuilder
which is a base class for other classes like SqlConnectionStringBuilder etc.
You can create an instance of DbConnectionStringBuilder and in my case I needed to have one configurable connection string that I could get information from -- regardless of the database provider type. A few options if you need this flexibility -- you could create the appropriate ConnectionStringBuilder for your provider as others have suggested -- this would likely be required for most cases where provider-specific properties are needed.
Or if you want to read just a couple generic properties, you could use DbConnectionStringBuilder if you just need the user id and password for example.
This sample should work for ANY connection string that includes user id and password.
DbConnectionStringBuilder db = new DbConnectionStringBuilder();
db.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
var username = db["User Id"].ToString();
var password = db["Password"].ToString();
SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string myUser = con.UserID;
string myPass = con.Password;
var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString)
var user = builder.UserID;
var password = builder.Password;
You can get the connection string from the following
SqlConnectionStringBuilder yourconn = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string password = yourconn.Password;
You can then get the substring you are looking for .
Just to add a bit to Tomas Walek's answer.
This approach would work only if "User ID" in the connection string is capitalized correctly. Oracle provider accepted "User Id" OK, but SqlConnectionStringBuilder did not work.
public static class DbConnectionFactory
{
public static ConnectionStringSettings AppConnectionSettings = ConfigurationManager.ConnectionStrings["{A connection string name}"];
public static SqlConnectionStringBuilder AppConnBuilder = new SqlConnectionStringBuilder(AppConnectionSettings.ConnectionString);
public static string DbUserID
{
get
{
return AppConnBuilder.UserID;
}
set { }
}
}
add a reference to System.Configuration and then use:
using System.Configuration;
string MyDBConnection = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(MyDBConnection);
string UserID = builder.UserID;
string Password = builder.Password;
string ServerName = builder.DataSource;
string DatabaseName = builder.InitialCatalog;
public static string GetConnectionSettings(string searchSetting )
{
var con = ConfigurationManager.ConnectionStrings["yourConnectionHere"]‌​.ConnectionString;
String[] myString = con.Split(';');
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < myString.Count(); i++)
{
String[] con3 = myString[i].Split('='); dict.Add(con3[0], con3[1]);
}
return dict[searchSetting];
}
for searchSetting you can use what you want "User Is" or password.
another way is to use regular expression (which I did), with a more forgiving pattern, to handle different ways a user id could be provided on the connection string:
public static string GetUserIdFromConnectionString(string connectionString)
{
return new Regex("USER\\s+ID\\=\\s*?(?<UserId>\\w+)",
RegexOptions.IgnoreCase)
.Match(connectionString)
.Groups["UserId"]
?.Value;
}
Extension method to get "User Id" from connectionString in DbConnection:
using System;
using System.Data.Common;
using System.Text.RegularExpressions;
namespace DemoProject.Helpers
{
public static class DbConnectionExtensions
{
public static string GetUserId(this DbConnection connection)
{
const string userIdPattern1 = "User[ ]*Id";
const string userIdPattern2 = "UID";
var connectionString = connection.ConnectionString;
foreach (var item in connectionString.Split(';'))
{
var index = item.IndexOf('=');
if (index == -1)
continue;
var property = item.Substring(0, index).Trim();
if (Regex.IsMatch(property, userIdPattern1, RegexOptions.IgnoreCase) ||
Regex.IsMatch(property, userIdPattern2, RegexOptions.IgnoreCase))
{
var userId = item.Substring(index + 1).Trim();
return userId;
}
}
throw new Exception("Couldn't find \"User Id\" in connectionString");
}
}
}
Example #1 of using:
using DemoProject.Helpers;
using Oracle.ManagedDataAccess.Client;
namespace DemoProject
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Data Source=(DESCRIPTION=" +
"(ADDRESS=(PROTOCOL=TCP)(HOST=oracle19c-vm)(PORT=1521))" +
"(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)));" +
"User Id=JOHN;" +
"Password=pwd123";
var connection = new OracleConnection(connectionString);
var userId = connection.GetUserId();
}
}
}
Example #2 of using:
using DemoProject.Helpers;
using Npgsql;
namespace DemoProject
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Server=postgre-vm;" +
"User Id=JOHN;" +
"Password=pwd123;" +
"Database=DEV1";
var connection = new NpgsqlConnection(connectionString);
var userId = connection.GetUserId();
}
}
}
Also you can add the 2nd extension method to get the password
var connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connString.Split(';');
string userId;
string password;
for(var i = 0; i < tokens.Length; i++) {
var token = tokens[i];
if(token.StartsWith("User ID"))
userId = token.Substring(token.IndexOf("=") + 1);
if(token.StartsWith("Password"))
password = token.Substring(token.IndexOf("=") + 1);
}
string connectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connectionString.Split(';').Select(n => n.Split('=');
string userId = tokens.First(n => n[0].Equals("User ID").Select(n => n[1]);
string password = tokens.First(n => n[0].Equals("Password").Select(n => n[1]);

Categories