Skip to content
This repository has been archived by the owner on Oct 4, 2021. It is now read-only.

MSAL example for Non Interactive Pat Generation #301

Open
cveld opened this issue Nov 30, 2020 · 0 comments
Open

MSAL example for Non Interactive Pat Generation #301

cveld opened this issue Nov 30, 2020 · 0 comments

Comments

@cveld
Copy link

cveld commented Nov 30, 2020

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?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant