【问题标题】:Cannot verify AAD token obtained via adal-angular4无法验证通过 adal-angular4 获得的 AAD 令牌
【发布时间】:2019-06-11 03:32:34
【问题描述】:

我有一个使用 Angular 6 编写的 Web 应用程序,使用 adal-angular4 package 通过 AAD 执行身份验证。我正在尝试让 UI 使用此令牌与后端服务进行通信。但是,在尝试调用服务器的 API 时,即使应该关闭所有验证,我也会不断收到 401 Unauthorized 响应。使用jwt.io 检查令牌会在页面底部产生“无效签名”错误,但否则令牌是可读的。

对于 AAD 配置,前端应用程序和后端服务都注册为单独的 AAD 应用程序,因此任何对 clientIdclientAppId 的引用指的是客户端的应用程序 ID,而 apiServiceId 是指后端服务的应用程序 ID .我还在后端应用注册中暴露了一个范围,为该范围的前端应用注册添加了一个 API 权限,并在后端应用中授权了前端应用。我还为这两个服务的 id 令牌和访问令牌启用了隐式授权。以下是相关代码:

app.module.ts:

// imports

@NgModule({
  declarations: [ ... ],
  imports: [ ... ],
  providers: [
    AdalService,
    AdalGuard,
    { provide: HTTP_INTERCEPTORS, useClass: AdalInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';

import { AdalService } from 'adal-angular4';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Tour of Heroes';

  constructor(private adalService: AdalService) {
    adalService.init(environment.adalConfig);
  }
}

toolbar.component.ts(登录按钮所在的位置):

import { Component, OnInit } from '@angular/core';
import { AdalService } from 'adal-angular4';

@Component({
  selector: 'app-toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent implements OnInit {

  constructor(private adalService: AdalService) { }

  ngOnInit() {

    this.adalService.handleWindowCallback();

    console.log(this.adalService.userInfo);
  }

  login() {
    this.adalService.login();
  }

  logout() {
    this.adalService.logOut();
  }

  get authenticated(): boolean {
    return this.adalService.userInfo.authenticated;
  }

  get username(): string {
    return this.adalService.userInfo.userName;
  }
}

环境.ts:

export const environment = {
  production: true,
  adalConfig: {
    tenant: 'MyTenant.onmicrosoft.com',
    clientId: '<clientId>',
    endpoints: {
      "https://localhost:8443/api": "<apiServiceId>"
    }
  }
};

来自 Startup.cs:

// TODO: Put strings in config
const string tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
const string clientAppId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
appBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        Tenant = "MyTenant.onmicrosoft.com",
        TokenValidationParameters = new TokenValidationParameters
        {
            // Authentication still fails when all bools below are set to false.
            NameClaimType = ClaimTypes.Name,
            AuthenticationType = "AADJwt",
            ValidateLifetime = true,
            RequireExpirationTime = true,
            ValidateAudience = true,
            ValidAudiences = new[]
            {
                clientAppId,
            },
            ValidateIssuer = true,
            ValidIssuers = new[]
            {
                $"https://sts.windows.net/{tenantId}/",
                $"https://login.microsoftonline.net/{tenantId}/",
            },
        }
    });

Controller.cs:

[Authorize]
public class MyController : ApiController
{
    // APIs
}

这是根据 jwt.io 的令牌外观:

标题:

{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "nbCwW11w3XkB-xUaXwKRSLjMHGQ",
  "kid": "nbCwW11w3XkB-xUaXwKRSLjMHGQ"
}

有效载荷:

{
  "aud": "<clientId>",
  "iss": "https://sts.windows.net/<tenantId>/",
  "iat": 1547682045,
  "nbf": 1547682045,
  "exp": 1547685945,
  "aio": "AVQAq/8KAAAAONOm6T/DrjjHFUTe/uPcsFcv2Iye85/EtY+cFYyq+X69OcQlHyqqPcYF0cjRWHyIRnnkcr7PkSTHp5bRb40AGUhVS5yuG53RCO0lNAQCBfE=",
  "amr": [
    "pwd",
    "rsa"
  ],
  "email": "asdf@asdf.com",
  "family_name": "asdf",
  "given_name": "asdf",
  "idp": "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/",
  "ipaddr": "x.x.x.x",
  "name": "asdf asdf",
  "nonce": "1a80bf29-e720-4abc-91c3-bc37c066286a",
  "oid": "f4f2107f-a760-4db4-b5d6-9a9fb6d2cb6b",
  "sub": "ll04ffs2YHBR0esHBJp9vevJEbgITRC9ushAQdZbB7U",
  "tid": "d93850bc-6bc9-4a51-9975-13e297ee0710",
  "unique_name": "asdf@asdf.com",
  "uti": "A7mEPuQ6REKQIFShTCoDAA",
  "ver": "1.0"
}

为什么我的身份验证会失败?我要验证的令牌中的所有内容似乎都符合我的预期,所以我不知道为什么我一直收到 401。jwt.io 无法验证签名的事实让我觉得那里有问题;会是什么?

编辑:添加了 AAD 设置信息并提供了更新的 environment.ts,其中包括 endpoints 数组。根据我的阅读,AdalInterceptor 将根据endpoints 自动获取和注入访问令牌。我得到的令牌在功能上与上面显示的令牌相同。我还缺少其他配置吗?

【问题讨论】:

  • 这看起来像是您要发送的 ID 令牌。您的前端通常应该使用 API 的客户端 ID 或应用 ID URI 为您的 API 获取访问令牌。
  • 有什么区别?你知道如何使用 adal-angular4 获取访问令牌吗?我对 Web 开发很陌生,所以很多这对我来说都是陌生的

标签: c# angular azure-active-directory


【解决方案1】:

原来我在启动时以错误的顺序设置了中间件。请参阅this answer,其中询问者必须在管道中更早地注册 AAD 身份验证才能使事情正常进行。否则,无论配置如何,您每次都可能只会收到 401 响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2016-12-29
    • 2022-06-18
    • 2019-07-14
    • 2020-03-08
    • 2018-01-13
    • 2014-12-29
    相关资源
    最近更新 更多