How do I get the Visual Studio Online credentials

2020-07-25 09:40发布

问题:

When you sign into Visual Studio 2013, it caches your profile and credentials in the registry:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\ConnectedUser\IdeUser\Cache
HKEY_CURRENT_USER\Software\Microsoft\VSCommon\12.0\ClientServices\TokenStorage\VisualStudio\IdeUser

When you authenticate with Visual Studio Online using the TFS API, it then copies the credentials to:

HKEY_CURRENT_USER\Software\Microsoft\VSCommon\12.0\ClientServices\TokenStorage\VisualStudio\VssApp

use tfs = new TfsTeamProjectCollection(Uri "https://ctaggart.visualstudio.com/DefaultCollection")
tfs.Authenticate()

How do I use these values in C# or F# using the Visual Studio or TFS APIs?

I've gathered that Vss may mean Visual Studio Services. There is a Microsoft.VisualStudio.Services.Common.CredentialsCacheManager and another in Microsoft.TeamFoundation.Client, but I'm not sure how to use either. It has a ContainCredentials, GetCredentials, and DeleteCredentials, so it looks promising. The GetCredentials returns a TfsCredentialCacheEntry, which has a Credentials property to get the System.Net.NetworkCredential which is exactly what I'm looking for.

I have no idea how to use CredentialsCacheManager, but here is what I tried.

let ccm = Microsoft.TeamFoundation.Client.CredentialsCacheManager(@"Software\Microsoft\VSCommon\12.0\ClientServices\TokenStorage\VisualStudio", false)
ccm.ContainsCredentials("IdeUser", Uri "ideuser:https://app.vssps.visualstudio.com:vssuser:federated")

Using Process Monitor, it shows that CredentialsCacheManager is either not what I'm looking for or I don't know how to use it:

回答1:

I figured it out. The Microsoft.TeamFoundation.Client.TfsClientCredentialStorage has what I'm looking for. I put all the example code in a F# script as a gist. I'll copy it here as well:

#r "Microsoft.TeamFoundation.Client"
#r "Microsoft.VisualStudio.Services.Common"
#r "System.Net.Http"

open System
open Microsoft.TeamFoundation.Client

// retrieve VssToken

// for the logged in user "IdeUser"
let vssTokenIdeUser = TfsClientCredentialStorage.RetrieveConnectedUserToken()

let tokenStorage = Microsoft.VisualStudio.Services.Common.TokenStorage.VssTokenStorageFactory.GetTokenStorageNamespace "VisualStudio"
let vssTokens = tokenStorage.RetrieveAll "VssApp" |> Array.ofSeq
for t in vssTokens do
    printfn "%s %s %s %s" t.Resource t.Type (t.GetProperty "UserId") (t.GetProperty "UserName")

// create a TfsClientCredentials by retrieving an IssuedToken

let ccs = TfsClientCredentialStorage()
let ct = ccs.RetrieveToken(Uri "https://ctaggart.visualstudio.com", Microsoft.VisualStudio.Services.Common.VssCredentialsType.Federated) :?> CookieToken
let cc = CookieCredential(false, ct)
let tcc = TfsClientCredentials cc

// use the TfsClientCredentials to authenticate with 

let tfs = new TfsTeamProjectCollection(Uri "https://ctaggart.visualstudio.com/DefaultCollection", tcc)
tfs.Authenticate()