我如何使用授权例程提供的VSTS OAUTH2承载令牌



我正在编写MVC5 Web应用程序,以便我在Visual Studio Team Services(VSTS)中查询我们的工作项目。

遵循这样的教程,我成功地创建了该应用程序,以便它可以使用我为开发目的创建的个人访问令牌(PAT)检索我想要的工作项目。我还通过密切关注此处可用的示例,成功创建了整个OAuth2流程,以便将用户带到VST,要求授权我的应用程序,然后返回到我的回调页面。正确的回调URL包括访问令牌,刷新令牌等。到目前为止,一切都很好。

我将用户的刷新令牌存储在我的数据库中的用户记录中,以及到期日期和时间(这样我知道如果他们在访问令牌过期后尝试访问该应用程序,请刷新令牌)。

我的问题是,我无法弄清楚如何为用户使用访问令牌,而不是在查询VST的C#代码中使用自己的PAT。我使用的代码在下面(它实际上与我上面链接到的github的示例中的代码相同),并且正常工作,但是如您所见,它使用的是使用PAT。相反,我如何使用用户的访问令牌,目前我只是在API返回时将其视为string(也许是错误的?)。

public class GetFeatures
{
    readonly string _uri;
    readonly string _personalAccessToken;
    readonly string _project;
    public GetFeatures()
    {
        _uri = "https://myaccount.visualstudio.com";
        _personalAccessToken = "abc123xyz456"; //Obviously I've redacted my actual PAT
        _project = "My Project";
    }
    public List<VSTSFeatureModel> AllFeatures()
    {
        Uri uri = new Uri(_uri);
        string personalAccessToken = _personalAccessToken;
        string project = _project;
        VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);
        //create a wiql object and build our query
        Wiql wiql = new Wiql()
        {
            Query = "Select [State], [Title] " +
                    "From WorkItems " +
                    "Where [Work Item Type] = 'Feature' " +
                    "And [System.TeamProject] = '" + project + "' " +
                    "And [System.State] <> 'Removed' " +
                    "Order By [State] Asc, [Changed Date] Desc"
        };
        //create instance of work item tracking http client
        using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
        {
            //execute the query to get the list of work items in the results
            WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;
            //some error handling                
            if (workItemQueryResult.WorkItems.Count() != 0)
            {
                //...do stuff                   
            }
            return null;
        }
    }
}

您需要使用VssOAuthCredential而不是VssBasicCredential

在大量猜测之后,由于VSTS .NET客户端库的记录很差,因此我发现VssOAuthCredential似乎已被弃用。我能够通过更换

来使我的代码示例工作。
VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken)

VssOAuthAccessTokenCredential credentials = new VssOAuthAccessTokenCredential(AccessToken);

accessToken是包含用户OAuth访问令牌的string

该框架似乎没有用,哈哈...

我目前正在研究一个用于备份VSTS帐户的项目,并且我正在通过HTTPRequests将其全部完成到RETS API。

public List<int> GetItemIDs()
    {
        HttpClient client = auth.AuthenticateHTTP(new HttpClient());
        string content = $@"{{""query"": ""Select[System.Id] From WorkItems order by[System.CreatedDate] desc"" }}";
        StringContent stringContent = new StringContent(content, Encoding.UTF8, "application/json");
        string endpoint = "DefaultCollection/_apis/wit/wiql?api-version=1.0";
        Uri requesturl = UriCombine(baseurl, endpoint);
        HttpResponseMessage response = client.PostAsync(requesturl, stringContent).Result;
        string result = response.Content.ReadAsStringAsync().Result;
        var json = Newtonsoft.Json.JsonConvert.DeserializeObject<QueryResponse>(result);
        return json.workItems.Select(x => x.id).ToList();
    }
public List<string> ListToString200(List<int> ids) //Writes all IDs into comma seperated strings of up to 200 IDs and puts them into a List.
        {
            List<string> idStrings = new List<string>();
            if (ids.Count > 200)
            {
                while (ids.Count > 200)
                {
                    List<int> t = new List<int>();
                    var IDs = ids.Take(200);
                    ids.Remove(200);
                    foreach (var item in IDs)
                    {
                        t.Add(item);
                    }
                    var ID = t.ConvertAll(element => element.ToString()).Aggregate((a, b) => $"{a},{b}");
                    idStrings.Add(ID);
                }
            }
            else if (ids.Count > 0)
            {
                var ID = ids.ConvertAll(element => element.ToString()).Aggregate((a, b) => $"{a}, {b}");
                idStrings.Add(ID);
            }
            return idStrings;
        }

private List<WorkItem> GetAllWorkItems()
        {
            List<int> ids = GetItemIDs();
            List<WorkItemsContainer> Responses = new List<WorkItemsContainer>();
            List<WorkItem> ResultList = new List<WorkItem>();
            List<string> idStrings = ListToString200(ids);
            using (HttpClient client = new HttpClient())
            {
                auth.AuthenticateHTTP(client);
                foreach (var item in idStrings)
                {
                    WorkItemsContainer WorkItem = new WorkItemsContainer();
                    string featurePath = $"DefaultCollection/_apis/wit/workitems?ids={item}&$expand=all&api-version=1.0";
                    Uri requestUri = Authenticator.UriCombine(baseurl, featurePath);
                    HttpResponseMessage response = client.GetAsync(requestUri).Result;
                    string result = response.Content.ReadAsStringAsync().Result;
                    result = result.Replace("System.", "System");
                    WorkItem = JsonConvert.DeserializeObject<WorkItemsContainer>(result);
                    Responses.Add(WorkItem);
                }
            }
            foreach (var item in Responses)
            {
                foreach (var x in item.value.ToList<WorkItem>())
                {
                    WorkItemsToJsonFile(x);
                    ResultList.Add(x);
                }
            }
            return ResultList;
        }

使用固定登录更容易,不需要OAuth2,尽管手动执行oauth2并不难得多,只需将令牌变成携带者身份验证标头...

最新更新