Connect to MongoDB from .Net application with SSH - c#

I connected shh tunnel and ForwardedPortLocal but mongo client does not connect .
Here is my expection "Additional information: Unable to connect to server localhost:27000: Invalid credential for database 'db_name'.."
var keyFile = new PrivateKeyFile(#"C:\Users\Desktop\mms_key.pem");
var username = "mms-user";
using (var client = new SshClient("dpmongo-0.sample.2121.mongodbdns.com",22, username, keyFile))
{
client.Connect();
var port = new ForwardedPortLocal("127.0.0.1", 27000, "localhost", 27000);
client.AddForwardedPort(port);
port.Start();
var credentials = MongoCredential.CreateMongoCRCredential("db_name", "user_name", "password");
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27000);
settings.Credentials = new[] { credentials };
var mongoEC2 = new MongoClient(settings);
var server = mongoEC2.GetServer();
var database = server.GetDatabase("db_name");
var collection = database.GetCollection<BsonDocument>("tag");
var query = Query.EQ("linkid", 2258021);
var userFound = collection.FindOne(query);
client.Disconnect();
}

string clientserver = "localhost";
string _port = "27000";
string mongo_username = "user_name";
string mongo_password = "password";
string databaseName = "db_name";
var connectionString = "mongodb://"
+ mongo_username + ":" + mongo_password + "#"
+ clientserver + ":" + _port + "/"
+ databaseName;
var server = new MongoClient(connectionString).GetServer();
//I tried this and it gave the same error on c#. This information was linked to my experiment on MongoCfee tools.

Related

LDAP Server not available error when using LDAPS authentication

string username = "username";
var con = new LdapConnection(new LdapDirectoryIdentifier(ADUtilities.LDAPServer, Convert.ToInt32(ADUtilities.LDAPPort), false, false));
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.ProtocolVersion = 3;
var clientCertificateFile = new X509Certificate();
clientCertificateFile.Import(ADUtilities.LDAPSSLCertificatePath);
con.ClientCertificates.Add(clientCertificateFile);
con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(VerifyServerCertificate); }
con.Credential = new NetworkCredential(username, ADPassword);
con.AuthType = AuthType.Negotiate;
con.Timeout = new TimeSpan(0, 1, 0);
con.Bind();
private bool VerifyServerCertificate(LdapConnection ldapConnection, X509Certificate certificate) {
X509Certificate2 certificate2 = new X509Certificate2(certificate);
return certificate2.Verify();
}
Error is coming in the line con.bind() that LDAP server is not available. Same code is working fine with port 389 but not with 636 i.e. LDAPS

Proxy authentication required(407) in some network

i tried below code to resolve the proxy authentication issue. But still the issue is persist.
Note: Some networks without using Proxy, it is working fine.
var INI = new IniFile(#"Settings.ini");
String scredUserName = INI.Read("UserName", "Credentials");
String sPassword = INI.Read("Password", "Credentials");
String sAPIKey = INI.Read("APIKey", "Credentials");
string sUserNamePassword = scredUserName + ":" + sPassword;
byte[] byteUserNamePassword = System.Text.ASCIIEncoding.ASCII.GetBytes(sUserNamePassword);
string encodedUserNamePassword = System.Convert.ToBase64String(byteUserNamePassword);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
encodedUserNamePassword);
client.DefaultRequestHeaders.Add("aw-tenant-code", sAPIKey);
String sProxyUserName = INI.Read("UserName", "Proxy Authentication");
String sProxyPassword = INI.Read("Password", "Proxy Authentication");
string sProxyUserNamePassword = sProxyUserName + ":" + sProxyPassword;
byte[] byteProxyUserNamePassword = System.Text.ASCIIEncoding.ASCII.GetBytes(sProxyUserNamePassword);
string encodedProxyUserNamePassword = System.Convert.ToBase64String(byteProxyUserNamePassword);
client.DefaultRequestHeaders.Add("Proxy-Authorization", "Basic " + encodedProxyUserNamePassword);
Posting the answer for my questions:-
I should have passed Proxy credentials along with proxy address.
WebProxy wbProxy = new WebProxy();
Uri newUri = new Uri(sProxyAddress);
wbProxy.Address = newUri;
wbProxy.Credentials = new NetworkCredential(sProxyUserName, sProxyPassword);
client.Proxy = wbProxy;

How to access MongoDB using GSSAPI authentication mechanism?

I am trying to connect to the MongoDB server through a ssl certificate using c#. I am getting a System.TimeoutException (A timeout occurred after 30000ms selecting a server using the CompositeServerSelector).
I started with connection via MongoClientSetting object. Here is the code:
MongoClientSettings settings = new MongoClientSettings();
settings.MaxConnectionLifeTime = new TimeSpan(12, 0, 0);
settings.UseSsl = true;
settings.VerifySslCertificate = false;
var cert = new X509Certificate2("mongoDBCAFile.cer");
settings.SslSettings = new SslSettings{
ClientCertificates = new[] { cert }
};
settings.Servers = new[]{
new MongoServerAddress("xyz1.intranet.companyname.com", 12345),
new MongoServerAddress("xyz2.intranet.companyname.com", 12345)
};
settings.ReplicaSetName = "replicaName";
var cred = MongoCredential.CreateGssapiCredential("username#intranet.companyname.com").WithMechanismProperty("SERVICE_NAME", "servicename");
settings.Credential = cred;
var client = new MongoClient(settings);
var database = client.GetDatabase("DatabaseName");
var collection = database.GetCollection<BsonDocument>("CollectionName");
//This is the place of error
var count1 = collection.CountDocuments(new BsonDocument());
I tried playing around with ConnectTimeout, SocketTimeout, and wTimeOut but the error was same.
I also tried doing the same thing using the connection string as mentioned here but I wouldn't figure out how to create a connection string with these many parameters.
Found the solution.
The issue was with authentication of the user with external server. MongoDB server was waiting for the clearance from this external server, but Because the authentication was never successfully, MongoDB always lead to System.TimeoutException.
Here is the fix code.
settings.ReplicaSetName = "replicaName";
SecureString pwd = new NetworkCredential("intranet/userName", "myPassword").securePassword;
var cred = MongoCredential.CreateGssapiCredential("username/intranet.companyname.com", pwd).WithMechanismProperty("SERVICE_NAME", "serviceName").WithMechanismProperty("CANONICALIZE_HOST_NAME", "true");
settings.Credentials = cred;

Jenkins returns (403) Forbidden when createItem in C#

I am trying to create a task with the Jenkins API.
The user has permissions but there is no way.
The error that throwing is 403.
public void CreateJobWihtXmlTemplateAndRazorRemplaceWhitAutoritazion()
{
var configData = File.ReadAllText(configCobol);
byte[] credentialBuffer = new UTF8Encoding().GetBytes("user" + ":" +"pass");
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(credentialBuffer));
webClient.UseDefaultCredentials = true;
webClient.Proxy.Credentials = CredentialCache.DefaultCredentials;
var jenkinsJobData = FactoryDataProvider.CreateJenkinsJobData();
var result = Razor.Parse(configData, jenkinsJobData);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(result);
const string FORMAT = "http://{0}:{1}/createItem?name={2}";
var path =
string.Format(
FORMAT,
"someserver.example.com",
"8080",
jenkinsJobData.ProjectName);
webClient.Headers["content-type"] = " application/xml";
string response = webClient.UploadString(
path,
"POST",
result
);
Assert.AreEqual(HttpStatusCode.OK, HttpStatusCode.OK);
}
Uncheck "Prevent Cross Site Request Forgery exploits"

Get location of client machine using ip address

I am trying to get the location of client machine using ip address. Client can access the internet only if
he/she provide the proxy authenication.
Let us say client need to access the 'www.google.com' on the browser then immediately Authenication Required
prompt window open and then client enter his/her username and password. But it is possible the few users does
not required the provide the authenication in order to access internet.
This segment of code does not helped me...
string url = "http://freegeoip.net/xml/";
WebClient wc = new WebClient();
WebProxy proxyObj = new WebProxy("http://freegeoip.net/xml/");
proxyObj.Credentials = CredentialCache.DefaultCredentials;
Uri uri = new Uri(url);
MemoryStream ms = new MemoryStream(wc.DownloadData(uri));
XmlTextReader rdr = new XmlTextReader(url);
XmlDocument doc = new XmlDocument();
ms.Position = 0;
doc.Load(ms);
ms.Dispose();
In the above code if i add network credential instance with username, password and domain then it's work perfectly
Instead of providing the default net credential in code itself, I need to get the username and password from the users(client
machine).
My question is how to prompt the Authentication Required Window and get the username and password to load the download from url
I would be glad if someone throw light on this issue...
Edit: Somehow basic authentication window prompt and now i can get the username and password which can use for credential
try
{
var reg = HttpContext.Current.Request;
if (!String.IsNullOrEmpty(reg.Headers["Authorization"]))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.Headers["Authorization"].Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
string url = "http://freegeoip.net/xml/";
WebClient wc = new WebClient();
WebProxy wProxy = new WebProxy();
ICredentials crd;
crd = new NetworkCredential("'" + cred[0] + "'", "'" + cred[1] + "'");
wProxy = new WebProxy("myproxy", true, null, crd);
wc.Proxy = wProxy;
Uri uri = new Uri(url);
string content = wc.DownloadString(uri);
}
else
{
try
{
//var reg = HttpContext.Current.Request;
if (String.IsNullOrEmpty(reg.Headers["Authorization"]))
{
var res = HttpContext.Current.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", "Basic realm = \"freegeoip\"");
//res.End();
}
}
catch (Exception ex)
{
}
}
}
catch(Exception ex)
{
}
But Still It throwing the "Unable to connect to the remote server"

Categories