public static void Main(string[] args) { var username = "******"; // This is your AAD username in the form [email protected]. var password = "******"; // This is your AAD password. var aadApplicationID = "[your AAD application ID]"; // Created when you register an AAD application: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications. var adalCredential = new UserPasswordCredential(username, password); var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common"); var result = authenticationContext.AcquireTokenAsync(VstsResourceId, aadApplicationID, adalCredential).Result; var token = new VssAadToken(result); var vstsCredential = new VssAadCredential(token); var connection = new VssConnection(new Uri("https://[your VSTS account name].visualstudio.com"), vstsCredential); var client = connection.GetClient <DelegatedAuthorizationHttpClient>(); var pat = client.CreateSessionToken( displayName: "Generated by sample code", tokenType: SessionTokenType.Compact, scope: "vso.work" ).Result; Console.WriteLine(pat.Token); }
public static async Task Main(string[] args) { //var username = "******"; // This is your AAD username in the form [email protected]. //var password = "******"; // This is your AAD password. var aadApplicationID = "872cd9fa-d31f-45e0-9eab-6e460a02d1f1";// "[your AAD application ID]"; // Created when you register an AAD application: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications. //var adalCredential = new UserPasswordCredential(username, password); var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common"); // var aadToken = await authenticationContext.AcquireTokenSilentAsync(VstsResourceId, aadApplicationID); var aadToken = await authenticationContext.AcquireTokenAsync(VstsResourceId, aadApplicationID, new UserCredential()); var token = new VssAadToken(aadToken); var vstsCredential = new VssAadCredential(token); var connection = new VssConnection(new Uri("https://app.vssps.visualstudio.com"), vstsCredential); var client = connection.GetClient <TokenHttpClient>(); var pat = client.CreateSessionTokenAsync( new SessionToken() { DisplayName = "Generated by sample code " + DateTime.UtcNow.ToString("o"), Scope = "app_token", TargetAccounts = new Guid[] { Guid.Parse("0efb4611-d565-4cd1-9a64-7d6cb6d7d5f0"), //mseng Guid.Parse("8b119ea1-2e2a-4839-8db7-8c9e8d50f6fa"), //msdata }, }, SessionTokenType.Compact, isPublic: false ).Result; Console.WriteLine(pat.Token); }
// Execute a WIQL (Work Item Query Language) query to return a list of open bugs. public async Task <IList <WorkItem> > QueryOpenBugs(string project, string[] fields) { var credentials = new VssAadCredential(GIT_IGNORE.Variables.AdoMagicWord1, GIT_IGNORE.Variables.AdoMagicWord2); // create a wiql object and build our query var wiql = new Wiql() { // NOTE: Even if other columns are specified, only the ID & URL will be available in the WorkItemReference Query = "Select [Id] " + "From WorkItems " + "Where [Work Item Type] = 'Task' " + "And [System.TeamProject] = '" + project + "' " + "And [System.State] <> 'Closed' " + "Order By [State] Asc, [Changed Date] Desc", }; // create instance of work item tracking http client using (var httpClient = new WorkItemTrackingHttpClient(new Uri(GIT_IGNORE.Variables.AdoUri__PROD__), credentials)) { // execute the query to get the list of work items in the results var result = await httpClient.QueryByWiqlAsync(wiql).ConfigureAwait(false); var ids = result.WorkItems.Select(item => item.Id).ToArray(); // some error handling if (ids.Length == 0) { return(Array.Empty <WorkItem>()); } // get work items for the ids found in query return(await httpClient.GetWorkItemsAsync(ids, fields, result.AsOf).ConfigureAwait(false)); } }
private VssAadCredential GetVSTSCredential() { var authenticationContext = new AuthenticationContext(Authority); #if FEATURE_CORECLR var platformParameters = new PlatformParameters(); #else var platformParameters = new PlatformParameters(PromptBehavior.Auto); #endif var authenticationResult = authenticationContext.AcquireTokenAsync(Resource, Client, RedirectUri, platformParameters).GetAwaiter().GetResult(); var credential = new VssAadCredential(new VssAadToken(authenticationResult)); return(credential); }
private VssAadCredential GetVSTSCredential() { var authenticationContext = new AuthenticationContext(Authority); #if NET_FRAMEWORK var platformParameters = new PlatformParameters(PromptBehavior.Auto); #else PlatformParameters platformParameters = null; // .NET Core does not support interactive auth. #endif var authenticationResult = authenticationContext.AcquireTokenAsync(Resource, Client, RedirectUri, platformParameters).GetAwaiter().GetResult(); var credential = new VssAadCredential(new VssAadToken(authenticationResult)); return(credential); }
static void Main(string[] args) { var credentials = new VssAadCredential(); var messageHandler = new VssHttpMessageHandler(credentials, new VssHttpRequestSettings()); Uri uri = new Uri(@"https://microsoft.visualstudio.com/"); GitHttpClient gitHttpClient = new GitHttpClient(uri, messageHandler.Credentials); var Repositories = gitHttpClient.GetRepositoriesAsync().Result; GitRepository repository = Repositories.FirstOrDefault(r => r.Name.ToLowerInvariant() == "Localization".ToLowerInvariant()); var gitBranchStatuss = gitHttpClient.GetBranchesAsync(repository.Id).Result; GitBranchStats gitBranchStatus = gitBranchStatuss.FirstOrDefault(branch => branch.Name.ToLowerInvariant() == "master"); var descriptor = new GitVersionDescriptor() { Version = gitBranchStatus.Name, VersionOptions = GitVersionOptions.None, VersionType = GitVersionType.Branch }; //GitItem item = gitHttpClient.GetItemAsync(repositoryId: repository.Id, path: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; VersionControlProjectInfo vvvvvv = new VersionControlProjectInfo(); List <GitItem> items = gitHttpClient.GetItemsAsync(repositoryId: repository.Id, scopePath: "/intl/af-za/loc/windows/lcl/aad/brokerplugin/microsoft.aad.brokerplugin.dll.lcl", recursionLevel: VersionControlRecursionType.OneLevel, includeContentMetadata: true, latestProcessedChange: true, download: true, includeLinks: false, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; List <GitCommitRef> aaaa = gitHttpClient.GetCommitsAsync(repositoryId: repository.Id, searchCriteria: new GitQueryCommitsCriteria(), skip: null, top: null, userState: null, cancellationToken: new CancellationToken()).Result; GitCommitChanges gitCommitChanges = gitHttpClient.GetChangesAsync(items[0].CommitId, repositoryId: repository.Id, top: null, skip: null, userState: null, cancellationToken: new CancellationToken()).Result; Stream ssss = gitHttpClient.GetItemContentAsync(repositoryId: repository.Id, path: items[0].Path, recursionLevel: VersionControlRecursionType.None, includeContentMetadata: true, latestProcessedChange: true, download: true, versionDescriptor: descriptor, userState: null, cancellationToken: new CancellationToken()).Result; using (MemoryStream memoryStream = new MemoryStream()) { ssss.CopyTo(memoryStream); // Use StreamReader to read MemoryStream created from byte array using (StreamReader streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray()))) { string fileString = streamReader.ReadToEnd(); } } }
private static async Task <int> Go(List <AzureDevOpsPATScopes> scopes, string[] organizations, string name, int?expiresIn, DateTime?expiration, string user, string password, IConsole console) { AzureDevOpsPATScopes scopeFlags = 0; foreach (var scope in scopes) { scopeFlags |= scope; } string patName = GetPatName(scopeFlags, organizations, name); if (expiresIn.HasValue && expiration.HasValue) { Console.WriteLine("May not specify both --expires-in and --expiration."); return(1); } if (string.IsNullOrEmpty(user) != string.IsNullOrEmpty(password)) { Console.WriteLine("Must specify both user + password, or neither."); return(1); } DateTime credentialExpiration = GetExpirationDate(expiration, expiresIn); VssCredentials credentials; if (!string.IsNullOrEmpty(user)) { credentials = new VssAadCredential(user, password); } else { credentials = await GetInteractiveUserCredentials(); } var patGenerator = new AzureDevOpsPATGenerator(credentials); var pat = await patGenerator.GeneratePATAsync(patName, scopeFlags, organizations, credentialExpiration); Console.WriteLine($"{patName} (Valid Until: {credentialExpiration}): {pat.Token}"); return(0); }
public static void Main(string[] args) { var username = "******"; var password = "******"; var aadApplicationID = "{the application ID}"; var adalCredential = new UserPasswordCredential(username, password); // make use of ADAL SDK var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/common"); var result = authenticationContext.AcquireTokenAsync(VstsResourceId, aadApplicationID, adalCredential).Result; var token = new VssAadToken(result); var vstsCredential = new VssAadCredential(token); var connection = new VssConnection(new Uri("https://dev.azure.com/{org name}"), vstsCredential); var client = connection.GetClient <DelegatedAuthorizationHttpClient>(); var pat = client.CreateSessionToken( displayName: "PAT Generate", tokenType: SessionTokenType.Compact, scope: "vso.work" ).Result; //print the token to verify the script Console.WriteLine(pat.Token); }
private async Task <VssConnection> GetConnectionAsync() { if (cachedConnection == null) { VssCredentials credentials; if (string.IsNullOrWhiteSpace(patvar)) { var azureTokenProvider = new AzureServiceTokenProvider(); var authenticationResult = await azureTokenProvider.GetAuthenticationResultAsync("499b84ac-1321-427f-aa17-267ca6975798"); credentials = new VssAadCredential(new VssAadToken(authenticationResult.TokenType, authenticationResult.AccessToken)); } else { var pat = Environment.GetEnvironmentVariable(patvar); credentials = new VssBasicCredential("nobody", pat); } cachedConnection = new VssConnection(new Uri(organization), credentials); } return(cachedConnection); }
// Logic goes between UI and web. made internal to be mocked for unit tests public async Task <ICredentials> GetTokenFromAccount( AccountAndTenant account, VSAccountProvider provider, bool nonInteractive, CancellationToken cancellationToken) { // get the ADAL creds for the user account var uniqueId = account.TenantToUse.UniqueIds.First(); var tenantId = account.TenantToUse.TenantId; // we are passed the flag as non-interactive. we realy want to know if we should prompt so // need to reverse the flag var shouldPrompt = !nonInteractive; AuthenticationResult result = null; NuGetUIThreadHelper.JoinableTaskFactory.Run(async() => { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var parent = IntPtr.Zero; if (_dte != null) { parent = new IntPtr(_dte.MainWindow.HWnd); } try { result = await provider.AcquireAdalTokenAsync( resource: VsoEndpointResource, tenantId: tenantId, identitifer: new UserIdentifier(uniqueId, UserIdentifierType.UniqueId), parentWindowHandle: parent, accountKeyForReAuthentication: account.UserAccount, prompt: shouldPrompt, cancellationToken: cancellationToken); } catch (AdalSilentTokenAcquisitionException) { result = null; } }); if (result == null) { return(null); } var aadcred = new VssAadCredential(new VssAadToken(result)); // create the session token var connection = new VssConnection(AccountManager.VsoEndpoint, aadcred); var delegatedClient = connection.GetClient <DelegatedAuthorizationHttpClient>(); // Create a scoped session token to the endpoint var sessionToken = await delegatedClient.CreateSessionToken( cancellationToken : cancellationToken, scope : SessionTokenScope); var cred = new NetworkCredential { UserName = account.UserAccount.DisplayInfo.UserName, Password = sessionToken.Token }; return(cred); }
public override VssCredentials GetVssCredentials(IHostContext context) { ArgUtil.NotNull(context, nameof(context)); Tracing trace = context.GetTrace(nameof(AadDeviceCodeAccessToken)); trace.Info(nameof(GetVssCredentials)); ArgUtil.NotNull(CredentialData, nameof(CredentialData)); CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out string serverUrl); ArgUtil.NotNullOrEmpty(serverUrl, nameof(serverUrl)); var tenantAuthorityUrl = GetTenantAuthorityUrl(context, serverUrl); if (tenantAuthorityUrl == null) { throw new NotSupportedException($"This Azure DevOps organization '{serverUrl}' is not backed by Azure Active Directory."); } LoggerCallbackHandler.LogCallback = ((LogLevel level, string message, bool containsPii) => { switch (level) { case LogLevel.Information: trace.Info(message); break; case LogLevel.Error: trace.Error(message); break; case LogLevel.Warning: trace.Warning(message); break; default: trace.Verbose(message); break; } }); LoggerCallbackHandler.UseDefaultLogging = false; AuthenticationContext ctx = new AuthenticationContext(tenantAuthorityUrl.AbsoluteUri); var queryParameters = $"redirect_uri={Uri.EscapeDataString(new Uri(serverUrl).GetLeftPart(UriPartial.Authority))}"; if (PlatformUtil.RunningOnMacOS) { throw new Exception("AAD isn't supported for MacOS"); } DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync("https://management.core.windows.net/", _azureDevOpsClientId, queryParameters).GetAwaiter().GetResult(); var term = context.GetService <ITerminal>(); term.WriteLine($"Please finish AAD device code flow in browser ({codeResult.VerificationUrl}), user code: {codeResult.UserCode}"); if (string.Equals(CredentialData.Data[Constants.Agent.CommandLine.Flags.LaunchBrowser], bool.TrueString, StringComparison.OrdinalIgnoreCase)) { try { if (PlatformUtil.RunningOnWindows) { Process.Start(new ProcessStartInfo() { FileName = codeResult.VerificationUrl, UseShellExecute = true }); } else if (PlatformUtil.RunningOnLinux) { Process.Start(new ProcessStartInfo() { FileName = "xdg-open", Arguments = codeResult.VerificationUrl }); } else { throw new NotImplementedException("Unexpected platform"); } } catch (Exception ex) { // not able to open browser, ex: xdg-open/open is not installed. trace.Error(ex); term.WriteLine($"Fail to open browser. {codeResult.Message}"); } } AuthenticationResult authResult = ctx.AcquireTokenByDeviceCodeAsync(codeResult).GetAwaiter().GetResult(); ArgUtil.NotNull(authResult, nameof(authResult)); trace.Info($"receive AAD auth result with {authResult.AccessTokenType} token"); var aadCred = new VssAadCredential(new VssAadToken(authResult)); VssCredentials creds = new VssCredentials(null, aadCred, CredentialPromptType.DoNotPrompt); trace.Info("cred created"); return(creds); }