arsalan younus
arsalan younus

Reputation: 63

VssClientCredentials with accesstoken credentials in VSTS authentication

I am reading licensing information of user from VSTS but it is not authenticating itself with Access Token credentials.

How do you authenticate with an access token?

string accessToken = $"{AccessTokenHere}";
VssOAuthAccessTokenCredential accessTokenCredentials = new VssOAuthAccessTokenCredential(new VssOAuthAccessToken(accessToken));
var credentials = new VssClientCredentials(accessTokenCredentials);

VssConnection connection = new VssConnection(new Uri(this.ServerUri), credentials);
var licensingHttpClient = connection.GetClient<LicensingHttpClient>();
var accountEntitlement = licensingHttpClient.GetAccountEntitlementAsync().Result;
var license = accountEntitlement.License;

Upvotes: 4

Views: 6796

Answers (3)

RickWeb
RickWeb

Reputation: 2105

This is how I did it using a Personal Access Token.

VssBasicToken token = new VssBasicToken(new NetworkCredential("", "string-token"));

VssCredentials credentials = new VssBasicCredential(token);

VssConnection connection = new VssConnection(connectionUri, credentials);

Upvotes: 1

AIsmaili
AIsmaili

Reputation: 81

I think, you can skip the following line, when you have the bearer token from an oauth2 authentication:

// skip this line in your code: var credentials = new VssClientCredentials(accessTokenCredentials);

For me, this code is working:

VssOAuthAccessTokenCredential credentials = new VssOAuthAccessTokenCredential(AccessToken);
VssConnection connection = new VssConnection(new Uri("https://dev.azure.com/[your org]"), credentials);
var client = connection.GetClient<ProjectHttpClient>();
var projects = client.GetProjects().Result;

Please also make sure, you register the correct scopes in your application for whatever you are trying to achieve.

Upvotes: 5

Cece Dong - MSFT
Cece Dong - MSFT

Reputation: 31013

Try the code below:

        String collectionUri = "https://{account}.visualstudio.com";
        VssBasicCredential creds = new VssBasicCredential("", personalaccesstoken);
        VssConnection connection = new VssConnection(new Uri(collectionUri), creds);
        var licensingHttpClient = connection.GetClient<LicensingHttpClient>();
        var accountEntitlement = licensingHttpClient.GetAccountEntitlementAsync().Result;
        var license = accountEntitlement.License;

About personal access token, you can refer to the link below:

https://learn.microsoft.com/en-us/vsts/accounts/use-personal-access-tokens-to-authenticate?view=vsts

Upvotes: 2

Related Questions