Angular 客户端需要 Web API 的访问令牌



我有一个由 OWIN 保护的 Web API,它要求用户使用 Azure Active Directory 进行身份验证。我可以使用使用Microsoft授权 URL 获得的访问令牌通过 Postman 发出请求。

但是,从我的 Angular 客户端(也受 Azure AD 保护(中,如果不重定向到 API,我就无法获取 Web API 的访问令牌。客户端应用(其客户端 ID 与服务器 API 不同(是否有任何方法检索需要在 API 请求的授权标头中使用的访问令牌?

您已在 Azure Active Directory 中注册了两个应用程序(UI 和 API(。您需要代表当前用户授予 API 的 UI 访问权限使用注册的 UI 应用程序 ID 登录用户,最后检索 API 的访问令牌。

这里是ng2-adal组件的伪代码:

import { Injectable } from '@angular/core';
@Injectable()
export class AuthconfigService {
  constructor() { }
  public get adalConfig(): any {
    return {
      tenant: 'yourTenant.onmicrosoft.com',
      clientId: 'UI AppId (GUID)',
      redirectUri: window.location.origin + '/',
      postLogoutRedirectUri: window.location.origin + '/'
    };
  }
  public get apiKey(): string
  {
    return "API AppId (GUID)";
  }
}

然后在您的 app.component.ts 中:

this.adalService.init(this.authconfigService.adalConfig);
this.adalService.login();
this.adalService.acquireToken(this.authconfigService.apiKey).subscribe(
      (data) => {
.....});

最新更新