azure-devops-dotnet-samples icon indicating copy to clipboard operation
azure-devops-dotnet-samples copied to clipboard

MSAL example for Non Interactive Pat Generation

Open cveld opened this issue 5 years ago • 0 comments

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
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 = "[email protected]";
            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<DelegatedAuthorizationHttpClient>();

            // 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?

cveld avatar Nov 30 '20 22:11 cveld