无法验证通过adal-angular4

时间:2019-01-17 00:25:16

标签: c# angular azure-active-directory

我有一个用adal-angular4 package用Angular 6编写的Web应用程序,以通过AAD执行身份验证。我正在尝试使UI使用此令牌与后端服务进行通信。但是,即使应关闭所有验证,在尝试调用服务器的API时,仍会收到401未经授权的响应。使用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;
  }
}

environment.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自动获取和注入访问令牌。我得到的令牌在功能上与上面显示的令牌相同。我还有其他配置吗?

1 个答案:

答案 0 :(得分:0)

因此,事实证明我在启动时以错误的顺序设置了中间件。请参阅this answer,在此请求者必须在管道中较早地注册AAD身份验证才能正常工作。否则,无论配置如何,每次都可能会得到401个响应。