如何在 angular 中使用 Azure devops REST API

How to consume Azure devops REST API in angular

我创建了一个 Angular 应用程序,我必须在其中使用 Azure DevOps REST API 来检索票证详细信息。我正在使用 @azure/msal-angular", "@azure/msal-browser" 包针对客户端 Azure-AD 验证用户。

我正在使用 this document,它表示 URL 的语法应该类似于 GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id},但对我来说不起作用

但是当我将 GET https://[ClientURL.com]/[resource/location]/_apis/wit/workitems?ids=123 粘贴到浏览器地址栏时,我得到 JSON 响应。

我正在使用我通过调用我的客户 url 来使用 REST 服务的令牌
GET https://[ClientURL.com]/[resource/location]/_apis/wit/workitems?ids=123

我正在使用 MsalInterceptor 拦截请求,这将添加身份验证 header。

我收到一条错误消息 Interceptor - acquireTokenSilent rejected with error. Invoking interaction to resolve.

我找不到适合 angular 的任何文档,并且无法理解我是否必须再次为 REST API 进行身份验证,或者 AD 身份验证应该没问题。

更新

该应用程序已使用 C# 构建。我的客户希望使用 Angular 开发它。 这是我的登录配置

export function MSALInstanceFactory(): IPublicClientApplication {
        return new PublicClientApplication({
            auth: {
                clientId: '' // my registered angular app clientId,
                authority: 'https://login.microsoftonline.com/my_tenentid',
                redirectUri: 'https://localhost:8080',
                
            },
            cache: {
              cacheLocation: 'localStorage'
            }
        })
        }
  

我正在使用 MSAL 对我的应用进行身份验证

loginMsal() {
  this.msalService.loginPopup().subscribe(
    (response: AuthenticationResult) => {
      this.loginSuccessfull(response)

    })
 }

需要帮助!

您需要检查 Azure 门户中的 application you registered 是否已被授予 Azure DevOps 权限。请参阅以下步骤以授予 Azure DevOps 权限。

导航到已注册的应用程序门户-->管理下的API权限-->添加权限-- >select Azure DevOps-->select 委派权限-->检查user_impersonation.

并且您可以添加在身份验证 header 中获得的访问令牌,如下例来自 here

var vstsApi = "https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=6.1-preview.3"
var xhr = new XMLHttpRequest();
                
xhr.open('GET', vstsApi, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);

有关详细信息,请参阅 Javascript Web App Sample

更新:

const tokenRequest = {
      scopes: [ "api://499b84ac-1321-427f-aa17-267ca6975798/.default" ]
 };

this.authService.instance.acquireTokenSilent(tokenRequest).then(tokenResponse => {
              
              var vstsApi = "https://dev.azure.com/myorg/myproje/_apis/wit/workitems/5?api-version=6.1-preview.3"
              var xhr = new XMLHttpRequest();
                
              xhr.open('GET', vstsApi, true);
              var res = xhr.setRequestHeader('Authorization', 'Bearer ' + tokenResponse.accessToken);
 })