Azure ConnectionString using totally wrong login credentials - asp.net-mvc

I have created an ASP.NET MVC website which accesses a database, both of which are hosted in azure. I have created a specific login and user to access the database and can see them in SSMS. I see the login screen for the website. The trouble is when I try to log in, the login fails telling me that the user cannot be found.
Here's where it starts getting strange. The login ID that cannot be found is not the login that I created or that which is in my web.config (or my app.config). Instead it is the master user that I have to access the db server and other areas of my azure resources.
Here is the section from the web.config on my PC that was used to publish to azure:
<connectionStrings>
<add name="CSSL" connectionString="Server=tcp:svrmysqlserver.database.windows.net,1433;Database=MyDatabase;User ID=sqlUser#svrmysqlserver;Password=q2wW£E;Encrypt=True;TrustServerCertificate=False;Connection Timeout=300;" providerName ="System.Data.SqlClient" />
</connectionStrings>
The Error message said
Login failed for user 'MasterUser'.
I added some debug code to get the connection strings that were available and being used on the server and tried again. I got the following:
Login failed for user 'MasterUser'.
ConfigurationManager[data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true]
ConfigurationManager[]
ConfigurationManager[Data Source=tcp:svrmysqlserver.database.windows.net,1433;Initial Catalog=MyDatabase;User ID=MasterUser#svrmysqlserver;Password=MasterPassword;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False]
ConfigurationManager[Data Source=tcp:svrmysqlserver.database.windows.net,1433;Initial Catalog=MyDatabase;User ID=MasterUser#svrmysqlserver;Password=MasterPassword;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False]
Database[Data Source=tcp:svrmysqlserver.database.windows.net,1433;Initial Catalog=MyDatabase;User ID=MasterUser#svrmysqlserver;Password=MasterPassword;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False]
I attach a code snippet in answer to the comment below - where did I get the output from? I added code in the handler to get the current values of the connection strings before returning. The function is on the data context and is the first attempt to read data from the database.
public ReturnInfo GetSystemRecord(out AppSystemRecord rec)
{
ReturnInfo ret = null;
rec = new AppSystemRecord();
//check that we have a hope of seeing this record - no records should have an ID of zero
try
{
var query = from x in SystemRecord select x; // ther should only ever be one
if (query.Count() == 0)
{
SetupAdminUser();
SystemRecord.Add(rec);
SaveChanges();
}
else
rec = query.FirstOrDefault();
ret = new ReturnInfo(); // defaults to all okay
if (rec.Status == SystemStatus.Created || rec.Status == SystemStatus.Updated)
SetupDefaultsForLookupTables();
rec.Status = SystemStatus.Normal;
SaveChanges();
}
catch (Exception e)
{
while (e.InnerException != null)
e = e.InnerException;
ret = new ReturnInfo(ErrorType.UnableToReadDomainObject, e.Message + "\r\n");
// THIS IS THE IMPORTANT BIT TO GET THE CONNECTION DATA
foreach (ConnectionStringSettings v in ConfigurationManager.ConnectionStrings)
{
ret.ErrorMessage += "ConfigurationManager[" + v.ConnectionString + "] " + "\r\n";
}
ret.ErrorMessage += "Database[" + Database.Connection.ConnectionString + "] " + "\r\n";
}
return ret;
}
I searched my solution for any uses of MasterUser in any file but found none, nor any references to the password, which was the correct MasterUser password.
I deleted both the website and database and started again to be sure there were no files lying around in the cloud but without any joy. Any ideas what is going on? Is there some sort of cache that I haven't invalidated? is there some rule whereby there must be a connection to the master?
Your help and ideas would be gratefully received.
Craig

Related

Azure DevOps Server 2019 Programmatially copy test case error Exception: 'TF237124: Work Item is not ready to save'."

I'm able to copy most test cases with this code (trying to copy shared steps to be part of the test case itself) but this one will not copy but I can not see any error message as to why - could anyone suggest anything else to try. See output from Immediate windows. Thanks John.
?targetTestCase.Error
null
?targetTestCase.InvalidProperties
Count = 0
?targetTestCase.IsDirty
true
?targetTestCase.State
"Ready"
?targetTestCase.Reason
"New"
foreach (ITestAction step in testSteps)
{
if (step is ITestStep)
{
ITestStep sourceStep = (ITestStep)step;
ITestStep targetStep = targetTestCase.CreateTestStep();
targetStep.Title = sourceStep.Title;
targetStep.Description = sourceStep.Description;
targetStep.ExpectedResult = sourceStep.ExpectedResult;
//Copy Attachments
if (sourceStep.Attachments.Count > 0)
{
string attachmentRootFolder = _tfsServiceUtilities.GetAttachmentsFolderPath();
string testCaseFolder = _tfsServiceUtilities.CreateDirectory(attachmentRootFolder, "TestCase_" + targetTestCase.Id);
//Unique folder path for test step
string TestStepAttachementFolder = _tfsServiceUtilities.CreateDirectory(testCaseFolder, "TestStep_" + sourceStep.Id);
using (var client = new WebClient())
{
client.UseDefaultCredentials = true;
foreach (ITestAttachment attachment in sourceStep.Attachments)
{
string attachmentPath = TestStepAttachementFolder + "\\" + attachment.Name;
client.DownloadFile(attachment.Uri, attachmentPath);
ITestAttachment newAttachment = targetTestCase.CreateAttachment(attachmentPath);
newAttachment.Comment = attachment.Comment;
targetStep.Attachments.Add(newAttachment);
}
}
}
targetTestCase.Actions.Add(targetStep);
targetTestCase.Save();
}
Since this code works for most test cases, this issue may come from the particular test case. In order to narrow down the issue, please try the following items:
Run the code on another client machine to see whether it works.
Try to modify this particular test case using the account API uses, to see whether it can be saved successfully.
Try validate the WorkItem prior to save. The validate() method will return an arraylist of invalid fields.

Connecting to Neo4j Aura with .NET Core 2.2 web api

I am trying to connect a to Neo4j Aura instance from a .NET core 2.2 web api. I understand I need the Neo4j .Net Driver v4.0.0-alpha01, but I do not seem to be able to connect. There aren't very many examples out there as this driver is new and so is Aura.
I keep getting:
Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again.
I configure the driver as such
public void ConfigureServices(IServiceCollection services)
{
string uri = "neo4j://1234567.databases.neo4j.io:7687";//not actual subdomain
string username = "neo4j";
string password = "seeeeeeecret";//not actual password
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password)));
}
and in my test controller i run this
private async Task<string> Neo4JTestAsync()
{
string db = "MyDb";
string message = "TESTMESSAGE";
IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(db));
try
{
var greeting = session.WriteTransactionAsync(async tx =>
{
var result = tx.RunAsync("CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
new { message });
var res = await result;
return "return something eventually";
});
return await greeting;
}
catch (Exception e)
{
return e.Message; // throws "Failed after retried for 6 times in 30000 ms. Make sure that your database is online and retry again"
}
finally
{
await session.CloseAsync();
}
}
I can't get the exact error message you do - but I'm pretty sure this is due to encryption - one of the big differences between the 1.x and 4.x drivers is the default position on Encryption - which is now off by default.
So you'll want to change your initialisation to:
services.AddSingleton(GraphDatabase.Driver(uri, AuthTokens.Basic(username, password), config => config.WithEncryptionLevel(EncryptionLevel.Encrypted)));
That should get you going. Also - make sure you stick with the neo4j:// protocol, as that'll route you properly.
Have you tried bolt:// in the connection string?
string uri = "bolt://1234567.databases.neo4j.io:7687";//not actual subdomain

clear cached TFS client credentials

Please help me to clear TFS cached credentials using c# code. I'm using TFS API to access source code hosted by the Dev ops TFS server at https://dev.azure.com
sometimes (after domain password is changed) it raises 401 error when access the source code server. Please find code sample used to connect below:
var u = "https://dev.azure.com/orgid";
var vssCred = new VssClientCredentials();
if (cacheCred)
vssCred.Storage = new VssClientCredentialStorage(); // tried with storage and without
Logger.Debug("getting vsts collection for url:{0}", u);
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, vssCred);
try
{
Logger.Debug("authenticating");
tpc.Authenticate();
tpc.GetService<VersionControlServer>();
it uses Microsoft.TeamFoundationServer.ExtendedClient.15.131.1 and Microsoft.TeamFoundationServer.Client.15.131.1 packages.
I've tried to clear cached credentials using the code like below:
IEnumerable<string> ClearCachedTokens(VssCredentials cred, Uri address)
{
if (cred == null) return null;
var res = new Collection<string>();
foreach (VssCredentialsType enumValue in Enum.GetValues(typeof(VssCredentialsType)))
try
{
var token = cred.Storage.RetrieveToken(address, enumValue);
if (token != null)
{
var tokenData = string.Join(";", token.Properties.Select(_ => string.Format("{0}={1}", _.Key, _.Value)));
Logger.Debug("got token {0} {1}", enumValue, tokenData);
cred.Storage.RemoveToken(address, token);
res.Add(address.ToString());
}
}
catch (Exception ec)
{
Logger.Warn("can't clear token type:{0} error:{1}", enumValue, ec.Message);
}
return res;
}
but it does not return any entry and the error still persist.
However error is gone when I delete %appdata%Local\Microsoft\Team Foundation\7.0\Cache content and run tf.exe get command. It asks me for login and password and then 401 error is not shown any more when tpc.Authenticate(); is executed.
How can I clear cached credentials in the Cache folder using the TeamFoundationServer.Client or TeamFoundationServer.ExtendedClient API?
The credential might have been saved in the Credential Manager store (Control Panel\All Control Panel Items\Credential Manager) in the Generic Credentials group.

Not able to get through webseal authentication using rest-assured

working on an automation assignment and i am trying to test a web service hosted on a webseal server. the issue is i have pretty my tried every method in rest assured to get to the response json but what i am getting is the authentication screen html.
here is some of my non working code. what i was expecting it the json but no matter what authentication method i run i get the webseal's authentication page only.
private String serviceTestGET(WebServiceTest serviceTest) {
System.out.println("Credential : " + userName + " -- " + password);
// RestAssured.
// RestAssured.authentication = basic(userName, password);
// RestAssured.authentication = digest(userId, password);
// RestAssured.authentication = oauth(consumerKey, consumerSecret,
// accessToken, secretToken);//form(userName, password);
// RestAssured.authentication = form(userId, password, config);
RestAssured.useRelaxedHTTPSValidation();
return given().get(serviceTest.getEntryPoint()).asString();
}
I have found the answer after googling a bit.
there are few things we have to consider that webseal is going to authenticate the request by throwing back a authentication form. once that form is authenticated its expected that you will use the same session(cookies) to access the application behind the webseal server.
so here is my working code
System.out.println("Credentials : " + username + " - " + password);
RestAssured.useRelaxedHTTPSValidation();
SessionFilter sessionFilter = new SessionFilter();
Map<String,String> cookies = given().
filter(sessionFilter).
param("username", username).
param("password", password).
param("login-form-type", "pwd").
expect().
statusCode(200).
when().
post("https://your-web-seal-server/pkmslogin.form").getCookies();
Reporter.log("Server Authenticated");
return given().filter(sessionFilter).cookies(cookies).expect().statusCode(200).
when().get(serviceTest.getEntryPoint()).asString();

Logged out when returning a file but cancelling download

I've got a simple action that returns a file from a database.
public ActionResult Download(int sbID)
{
var module = moduleRepo.Snackbar.First(m => m.Id == sbID);
var data = moduleRepo.SnackbarData.First(m => m.Id == sbID).FileData;
var filename = module.FileName + "." + module.FileType;
return File(data, MediaTypeNames.Application.Octet, filename);
}
Everything works fine, but when a user hit's the download button, and then hit's "Cancel" (instead of Save as or open) it seems like the session terminates, because the user logs out. I am using regular Microsoft Identity authentication.
What could be causing this?

Resources