Setting commit author in SharpSvn .NET library throws SvnRepisitoryIOException exception - authentication

If you have experience with using the SharpSvn .NET library, I could use your expertise in setting the commit author during an SVN commit. I've tried a few things, but they all throw an SvnRepisitoryIOException unless the user is saved in TortoiseSVN. However, I want to use different user credentials depending on the situation. If I've saved a user's default credentials, TortoiseSVN remembers them in Settings > Saved Data > Authenticated Data, and is able to commit a file using that authenticated user as the commit author. If you click "Clear" here, SharpSVN won't know who to authenticate during a commit.
Assume you have these directives in your class: using SharpSvn;
using SharpSvn.Security; I'm using the free version of VisualSVN server for Windows. And I have two users, one being named "user1" and password of "pass1" to keep things simple in the examples below that failed.
How can I prevent this exception from being thrown and commit using different users for the author (in my log of the commit)?
Attempt #1:
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Clear a previous authentication
client.Authentication.DefaultCredentials = new System.Net.NetworkCredential("user1", "pass1");
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}
Attempt #2:
using (SvnClient client = new SvnClient())
{
client.SetProperty(("", "svn:author", "user1");
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}
Attempt #3:
using (SvnClient client = new SvnClient())
{
client.Authentication.Clear(); // Clear predefined handlers
client.Authentication.UserNamePasswordHandlers
+= delegate(object obj, SharpSvn.Security.SvnUserNamePasswordEventArgs args)
{
args.UserName = "user1";
args.Password = "pass1";
};
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);
}

After getting the stack trace when running the application as an administrator, I was able to catch the exception using the framework and accept the non trusted certificate issuer.
*Unhandled Exception: SharpSvn.SvnRepositoryIOException: Commit Failed (details follow): ===> SharpSvn.SvnRepositoryIOException: Unable to connect to a repository at URL 'https://mycomputer/svn/demo_repo/demo_project/trunk/file.txt' --> SharpSvn.SvnRepositoryIOException: OPTIONS of '': Server certificate verification failed: issuer is not trusted (https://mycomputer)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, SvnException error, Object targets)
at SharpSvn.SvnClientArgs.HandleResult(SvnClientContext client, svn_error_t* error, Object targets)
.....*
New Code:
client.Authentication.Clear(); // Clear predefined handlers
client.Authentication.UserNamePasswordHandlers
+= delegate(object obj, SharpSvn.Security.SvnUserNamePasswordEventArgs args)
{
args.UserName = "user1";
args.Password = "pass1";
};
client.Authentication.SslServerTrustHandlers​ +=
delegate(object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = true; // Save acceptance to authentication store
};
SvnCommitArgs ca = new SvnCommitArgs();
ca.LogMessage = "svn log message created at " + DateTime.Now.ToString();
bool action = client.Commit(#"C:\demo_repo\demo_project\trunk\file.txt", ca);

Related

How to access a file server share from an ASP.NET Core web API application published in IIS within the same domain?

I need access to files that are in a files server in my LAN from my Angular app.
I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN
Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I don´t know how to do it.
When I try this
[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
string[] files = Directory.GetFiles(#"\\192.168.100.7\ofertashistorico");
return files;
}
I get this error
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'
It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.
I also do not know how to manage the issue of the credentials necessary to access said resource
Any idea, please?
Thanks
I am using below code and it works for me. Please check it.
Steps:
Navigate to the path like : \\192.168.2.50\ftp
Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.
You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.
Test Result
Sample code
[HttpGet("directorio")]
public IActionResult GetDirectoryContents()
{
string networkPath = #"ftp:\\192.168.2.50";
string userName = #"Administrator";
string password = "Yy16";
#region FtpWebRequest
var networkCredential = new NetworkCredential(userName, password);
var uri = new Uri(networkPath);
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = networkCredential;
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
}
#endregion
return Ok();
}

The request was aborted: Could not create SSL/TLS secure channel. (RestSharp, SSL Client Certificates)

I have following code which is calling an API using basic authentication and SSL client certificate but its throwing exception and giving me following error.
"The request was aborted: Could not create SSL/TLS secure channel."
I tried to find a solution on Google but failed to find any solution. Can anyone help me out on this. Thanks.
// Variables
string basicAuthenticationUserName = "username";
string basicAuthenticationPassword = "password";
string clientCertificateFilePath = "Path-To-Certificate-File";
string clientCertificatePassword = "certificate-password";
string url = "https://" + basicAuthenticationUserName + ":" + basicAuthenticationPassword + "#apiserverurl/apimethod";
// Creating RestSharp Request Object
var request = new RestRequest(Method.POST)
{
RequestFormat = DataFormat.Json,
OnBeforeDeserialization = resp =>
{
resp.ContentType = "application/json";
}
};
// Adding Headers
request.AddHeader("Content-Length", "0");
request.AddHeader("Accept", "application/x-null-message");
// Importing Certificates
var certificates = new X509Certificate();
certificates.Import(clientCertificateFilePath, clientCertificatePassword, X509KeyStorageFlags.PersistKeySet);
// Creating RestSharp Client Object
var client = new RestClient
{
BaseUrl = new Uri(url),
ClientCertificates = new X509CertificateCollection { certificates },
Authenticator = new HttpBasicAuthenticator(managingLou, basicAuthenticationPassword)
};
// Executing Request
var response = client.Execute<T>(request);
I have faced the similar issue. Let me mention the steps here for your help.
After the installation of windows service, I went through the following steps to fix the issue:
Go To Start > Run and type Services.msc
Select your service > Right click and choose Properties
Select the 2nd tab "Log On"
Select the radio button "This account"
Enter the username and password of currently log in user. (Make sure Its the same user who has installed the service)
Apply the changes
Start the service

Azure Scheduler SSL Certificate error

I have a WCF Cloud Service running in azure which I connect to from a .NET client. This is all working nicely and I have implemented security by enabling SSL (using a self signed certificate) and using active directory authorisation.
However, I have a number of scheduled jobs using the azure scheduler and these jobs call methods in the Cloud service but I am unable to setup the scheduled jobs as HTTPS jobs. They work fine as HTTP jobs but as soon as I change it to HTTPS I get the following error:
“Http Action - Request to host '.cloudapp.net' failed: TrustFailure The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
I tried just accepting all certificates by adding the following code to the WCF web role’s OnStart method:
ServicePointManager.ServerCertificateValidationCallback
= delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
But the callback never gets invoked
So I assume I have to somehow add client certificate authentication to the scheduler job? But I cannot work out how.
I am creating the job through the Microsoft.WindowsAzure.Management.Scheduler Api e.g:
var action = new JobAction();
action.Type = JobActionType.Https;
action.Request = new JobHttpRequest();
action.Request.Method = "POST";
action.Request.Uri = new Uri(serviceURI);
action.Request.Body = soap;
action.RetryPolicy = new RetryPolicy()
{
RetryType = RetryType.None,
RetryCount = null
};
action.Request.Headers = new Dictionary<string, string>()
{
{ "Content-Type", "text/xml" },
{ "SOAPAction", "\"http://tempuri.org/" + serviceInterfaceName + "/" + methodName + "\"" }
};
var result = schedulerClient.Jobs.CreateOrUpdate(jobName, new JobCreateOrUpdateParameters()
{
action = action,
StartTime = startTime,
Recurrence = new JobRecurrence()
{
Frequency = frequency,
Interval = interval
}
});
and I see that in the JobAction class there is a property of the Request object called Authentication, I thought perhaps I might need to use that but I can find no documentation on how to use it?
Alternatively, I could create the schedule job through powershell or the azure portal interface if anyone can tell me how to successfully create an HTTPS schedule job through either of those methods?
Many thanks,
kelly
Scheduler jobs fail because it can't trust this endpoint. You need to use a trusted certificate for HTTPS calls from Scheduler.

CRM OrganizationServiceProxy authentication issue

We have an issue where our web app calls to CRM via Microsoft.Xrm.Sdk OriganizationServiceProxy are failing to authenticate. The issue appears to be environment specific i.e. the calls work on our DEV web server but fail when the app is promoted to our System Test environment. The code that fails is as follows:
using (var serviceProxy = this.serviceFactory.Impersonate(userProvider.PrincipalUserName).ServiceProxy)
{
var countResult = serviceProxy.RetrieveMultiple(new FetchExpression(query));
int? count = 0;
var entity = countResult.Entities.FirstOrDefault();
if (entity != null)
{
count = (int?)((AliasedValue)entity["activity_count"]).Value;
}
return count.Value;
}
The error that appears in our logs is:
System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)
--- End of inner exception stack trace ---
I have double checked the apppool identity of the IIS site and CRM settings. Is there anything obvious here that we may have missed?
I found the connection to CRM Online was taking the longest time so I create one instance to pass round of the OrganizationServiceProxy with explicit credentials that I can easily switch between environments.
IServiceManagement<IOrganizationService> management = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(CrmUrl));
ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = CrmUserName;
credentials.UserName.Password = CrmPassword;
AuthenticationCredentials authCredentials = management.Authenticate(new AuthenticationCredentials { ClientCredentials = credentials });
SecurityTokenResponse securityTokenResponse = authCredentials.SecurityTokenResponse;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(management, securityTokenResponse);
orgProxy.EnableProxyTypes();
_xrmService = new XrmServiceContext(orgProxy)

LibGit2Sharp: Fetching fails with "Too many redirects or authentication replays"

Here's the code I'm using to fetch:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
var fetchOpts = new FetchOptions {Credentials = creds};
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
but it fails during fetch with the following exception:
LibGit2Sharp.LibGit2SharpException: Too many redirects or authentication replays
Result StackTrace:
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
at LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteSafeHandle remote, Signature signature, String logMessage)
at LibGit2Sharp.Network.DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options, Signature signature, String logMessage)
at LibGit2Sharp.Network.Fetch(Remote remote, FetchOptions options, Signature signature, String logMessage)
I have verified that the config file has the required remote name and that git fetch works from the command line. I found that the exception originates from libgit2\src\transport\winhttp.c but I couldn't come up with a workaround/solution.
I tried #Carlos' suggestion in the following way:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
CredentialsHandler credHandler = (_url, _user, _cred) => creds;
var fetchOpts = new FetchOptions { CredentialsProvider = credHandler };
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
I could fetch from public repos on github as well as from password protected private repos on bitbucket; however, I couldn't do the same for the repositories hosted over LAN at work. Turns out they were configured in a way which does not accept UsernamePasswordCredentials provided by libgit2sharp. The following modification allowed me to fetch from repositories over LAN:
CredentialsHandler credHandler = (_url, _user, _cred) => new DefaultCredentials();
(I'm trying to find out what is the exact difference between the two; if I get further insight into it, I'll update the answer.)
The shim that should make the Credentials option work is currently buggy (and is deprecated anyway), pass a CredentialsProvider instead as a callback.
This seems to be a very common error message.
We were getting it on pushes to GitHub, because credentials were disabled for security:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
We've solved it by enabling SAML SSO and doing the push outside the C# code, but perhaps using SSH keys somehow with the library or personal access tokens fixes the problem too.