microsoft / azure-devops-dotnet-samples

.NET/C# samples for integrating with Azure DevOps Services and Azure DevOps Server
https://docs.microsoft.com/azure/devops/integrate
MIT License
522 stars 518 forks source link

MSAL example for Non Interactive Pat Generation #301

Open cveld opened 3 years ago

cveld commented 3 years ago

I am trying to convert the ADAL based example for Non Interactive Pat Generation to MSAL.

It looks like AAD is providing me a valid access token to the Azure DevOps REST API. But when I try to connect it throws the following exception: VssUnauthorizedException: VS30063: You are not authorized to access https://spsprodeus24.vssps.visualstudio.com.

Program.cs is as follows:

MSAL program.cs ```csharp using Microsoft.Identity.Client; using Microsoft.VisualStudio.Services.Client; using Microsoft.VisualStudio.Services.DelegatedAuthorization; using Microsoft.VisualStudio.Services.DelegatedAuthorization.Client; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Net; using System.Security; using System.Threading.Tasks; namespace NonInteractivePatGenerationSampleMsal { class Program { async static Task Main(string[] args) { var username = "testuser@carlintveld.onmicrosoft.com"; var password = new NetworkCredential("", "password").SecurePassword; var aadApplicationID = "4f381a56-xxxx-xxxx-xxxx-redacted"; // Created when you register an AAD application: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications. var client = PublicClientApplicationBuilder.Create(aadApplicationID).WithAuthority("https://login.microsoftonline.com/1fea1d7a-95b0-4ebc-b422-bcc75a77c9a0/").Build(); var scopes = new string[] { "https://app.vssps.visualstudio.com/user_impersonation" }; var result = await client.AcquireTokenByUsernamePassword(scopes, username, password).ExecuteAsync(); var token = new VssAadToken("Bearer", result.AccessToken); var vstsCredential = new VssAadCredential(token); var connection = new VssConnection(new Uri("https://dev.azure.com/carlintveld"), vstsCredential); var vsoclient = connection.GetClient(); // the following invocation throws the exception: var pat = vsoclient.CreateSessionToken( displayName: "Generated by sample code", tokenType: SessionTokenType.Compact, scope: "vso.work" ).Result; Console.WriteLine(pat.Token); } } } ```

What do I need to do to fix this?