How can one supply credentials during a Fetch call? - libgit2sharp

We're not talking about SSH since it's not yet implemented, but how can I supply credentials for the repository before I perform a fetch via HTTP/HTTPS? There doesn't seem to be a parameter for a Credentials instance, and nothing when constructing a Repository instance for storing credentials.

Within the FetchFixture.cs file, there is a Fetch() test using credentials:
[SkippableFact]
public void CanFetchIntoAnEmptyRepositoryWithCredentials()
{
InconclusiveIf(() => string.IsNullOrEmpty(Constants.PrivateRepoUrl),
"Populate Constants.PrivateRepo* to run this test");
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Remote remote = repo.Network.Remotes.Add(remoteName, Constants.PrivateRepoUrl);
// Perform the actual fetch
repo.Network.Fetch(remote, new FetchOptions
{
Credentials = new Credentials
{
Username = Constants.PrivateRepoUsername,
Password = Constants.PrivateRepoPassword
}
});
}
}

Related

Insufficient privileges to complete the operation Add new user using Azure Active Directory Graph Client API

I am Trying to Add new user in my AD but getting error as insufficient privileges to complete the operation not able to understand which permission is required to the Azure Active Directory Graph API which will not have this issue below is my code snippet which is making api call to AD Graph
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace AuthenticationPortal
{
public class ActiveDirectoryClientModel
{
// These are the credentials the application will present during authentication
// and were retrieved from the Azure Management Portal.
// *** Don't even try to use these - they have been deleted.
static string clientID = ConfigurationManager.AppSettings["ida:ClientId"];
static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
static string domain = ConfigurationManager.AppSettings["ida:Domain"];
// The Azure AD Graph API is the "resource" we're going to request access to.
static string resAzureGraphAPI = "https://graph.windows.net";
// This is the URL the application will authenticate at.
static string authString = "https://login.microsoft.com/" + tenantId;
// The Azure AD Graph API for my directory is available at this URL.
static string serviceRootURL = "https://graph.windows.net/" + domain;
private ActiveDirectoryClient GetAADClient()
{
try
{
Uri serviceroot = new Uri(serviceRootURL);
ActiveDirectoryClient adClient = new ActiveDirectoryClient(serviceroot, async () => await GetAppTokenAsync());
return adClient;
}
catch (Exception ex)
{
return null;
}
}
private static async Task<string> GetAppTokenAsync()
{
try
{
// Instantiate an AuthenticationContext for my directory (see authString above).
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Create a ClientCredential that will be used for authentication.
// This is where the Client ID and Key/Secret from the Azure Management Portal is used.
ClientCredential clientCred = new ClientCredential(clientID, clientSecret);
// Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
// using the Client ID and Key/Secret as credentials.
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientCred);
// Return the access token.
return authenticationResult.AccessToken;
}
catch (Exception ex)
{
return null;
}
}
public async Task CreateUser()
{
var adClient = GetAADClient();
var newUser = new User()
{
// Required settings
DisplayName = "Atul Gandhale",
UserPrincipalName = "atulm#"+ domain,
PasswordProfile = new PasswordProfile()
{
Password = "Asdf1234!",
ForceChangePasswordNextLogin = true
},
MailNickname = "atulg",
AccountEnabled = true,
// Some (not all) optional settings
GivenName = "Atul",
Surname = "Gandhale",
JobTitle = "Programmer",
Department = "Development",
City = "Pune",
State = "MH",
Mobile = "1234567890",
};
try
{
// Add the user to the directory
adClient.Users.AddUserAsync(newUser).Wait();
}
catch (Exception ex)
{
}
}
}
}
Please help me out i have already send couple of hours but not able to get the solution for this.
You need following permission to create new user in azure portal from your application:
Permission Type : Delegated permissions
Permission Name : Directory.ReadWrite.All
You could see the official docs
Step: 1
Step: 2
Point To Remember:
Once you successfully added your permission afterwords you must have to add Grant consent as shown step 2.
PostMan Test:
Azure Portal:
Note: But my suggestion is to use Microsoft Graph API Which is mostly recommended now. For Microsoft Graph you could refer this docs

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.

accessing Twitter API from Google Apps Script

I'm trying to read in a Google sheet my Twitter timeline.
I've copied the following code reported in the GAS documentation about twitter authentication (omitting step 2 since I'm not using the code inside a UI):
function getTwitterService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth1.createService('twitter')
// Set the endpoint URLs.
.setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
.setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
.setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
// Set the consumer key and secret.
.setConsumerKey('mykey')
.setConsumerSecret('mysecret')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}
function authCallback(request) {
var twitterService = getTwitterService();
var isAuthorized = twitterService.handleCallback(request);
if (isAuthorized) {
return Logger.log('Success! You can close this tab.');
} else {
return Logger.log('Denied. You can close this tab');
}
}
function makeRequest() {
var twitterService = getTwitterService();
var response = twitterService.fetch('https://api.twitter.com/1.1/statuses/user_timeline.json');
Logger.log(response);
}
but I obtain the message error: Service not authorized. (row 292, file "Service", project "OAuth1").
What's wrong?
I needed to add the following line the first time I execute makeRequest:
var authorizationUrl = twitterService.authorize();
Logger.log(authorizationUrl);
Then, open the url read from the log and authorize the app.
After that, all works fine.

Azure notification hub installation c#

Can anyone help me with Azure notification hub, how to set up device installation form c# code. I have problem with the Installation object. How to set it to pass it as parameter to CreateOrUpdateInstallation method of hub client instance. It's not clear to me.
I have a hub on azure that works with device registration like charm in local, but uploaded on azure are not working. Now I wanna try with istalation.
thnx
update: after 4 days, I figured out, that you can't send notification to yourself. Azure somehow knows that you are sending notification to yours phone, and that's why my welcome message never delivered to my phone.
update: this is how now I install the device i my backend code:
[HttpGet]
[Route("api/push/test-installation")]
public async Task<IActionResult> NotificationInstalationTest()
{
string connectionString = "{{my connection string}}";
string hubName = "{{my hub name}}";
string token = "{{tokne}}";
NotificationHubClient hubClient = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
string notificationText = $"Test message for Azure delivery for Atila at: {DateTime.Now.ToShortTimeString()}";
var alert = new JObject
(
new JProperty("aps", new JObject(new JProperty("alert", notificationText))),
new JProperty("inAppMessage", notificationText)
).ToString(Newtonsoft.Json.Formatting.None);
IList<string> tags = new List<string>();
tags.Add("email");
IDictionary<string, string> pushVariables = new Dictionary<string, string>();
pushVariables.Add( "email", "atila#panonicit.com" );
Installation installation = new Installation();
installation.InstallationId = Guid.NewGuid().ToString();
installation.Platform = NotificationPlatform.Apns;
installation.PushChannel = token;
installation.Tags = tags;
installation.PushVariables = pushVariables;
await hubClient.CreateOrUpdateInstallationAsync(installation);
NotificationOutcome result = await hubClient.SendAppleNativeNotificationAsync(alert);
return Ok("Success");
}
Now when I hit this endpoint with Postman it works, if the same endpoint call comes from iOS it not works!
thnx
How to set it to pass it as parameter to CreateOrUpdateInstallation method of hub client instance. It's not clear to me.
Based on my understanding, you are registering the notification hub from your backend using the installation model. For your WebAPI project, assuming your method for create/update an installation as follows:
InstallationController.cs
//PUT api/installation
public async Task<HttpResponseMessage> Put(DeviceInstallation deviceUpdate)
{
Installation installation = new Installation();
installation.InstallationId = deviceUpdate.InstallationId;
//TODO:
await hub.CreateOrUpdateInstallationAsync(installation);
return Request.CreateResponse(HttpStatusCode.OK);
}
For your mobile client, you could refer to the following method:
private async Task<HttpStatusCode> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation)
{
using (var httpClient = new HttpClient())
{
//TODO: set your authorization header
//httpClient.DefaultRequestHeaders.Authorization
var putUri =$"{your-backend-endpoint}/api/installation";
string json = JsonConvert.SerializeObject(deviceInstallation);
var response = await httpClient.PutAsync(putUri, new StringContent(json, Encoding.UTF8, "application/json"));
return response.StatusCode;
}
}
Moreover, for more details you could refer to Registration management and here for building backend with the registration model to build your backend using the installation model.

How to provide credentials to Fetch() and Pul() methods?

I'm looking for a nice clean example of how to do a pull using lidgit2sharp. I took the example here which does a fetch, but the reference to Credentials is throwing an exception.
using (var repo = new Repository(workingDir, null))
{
Remote remote = repo.Network.Remotes.Add("master", repoUrl);
repo.Network.Fetch(remote,
{
Credentials credentials = new Credentials
{
Username = "username",
Password = "password"
}
});
}
The exception is Cannot create an instance of the abstract class or
interface 'LibGit2Sharp.Credentials'
It's telling you in the error: Credentials is an abstract class, interface, whatever.
Try this:
Credentials credentials = new UsernamePasswordCredentials()
{
Username = "username",
Password = "password"
}

Resources