簡體   English   中英

如何使用授權例程提供的VSTS OAuth2承載令牌?

[英]How do I use the VSTS OAuth2 Bearer Token provided by the authorization routine?

我正在編寫一個MVC5 Web應用程序,以允許我查詢Visual Studio Team Services(VSTS)中的工作項。

有跟着教程像這一個這一個我已經成功地創建應用程序,以便它將檢索工作項我想用個人訪問令牌(PAT),我為發展而創建。 通過密切關注此處提供的示例,我還成功創建了整個OAuth2流程,從而使用戶進入VSTS,要求對我的應用程序進行授權,然后返回到我的回調頁面。 回調URL正確包含用戶的訪問令牌,刷新令牌等。 到現在為止還挺好。

我將用戶的“刷新令牌”以及到期日期和時間存儲在我的數據庫中(這樣,如果他們在訪問令牌過期后嘗試訪問應用程序,就可以刷新令牌)。

我的問題是我無法弄清楚如何為用戶使用訪問令牌,而不是在查詢VSTS的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到REST 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並不困難,只需將令牌轉換為承載身份驗證標頭即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM