我正在尝试从 Azure 资源 API 获取数据:https ://management.azure.com/subscriptions/%7BsubscriptionId%7D/tagNames?api-version=2018-05-01
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { MsAdalAngular6Service } from 'microsoft-adal-angular6';
@Injectable({
providedIn: 'root'
})
export class AzureApiService {
httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + this.adalSvc.accessToken,
//'Access-Control-Allow-Origin' : '*'
})}
azure_url = "https://management.azure.com/subscriptions/xxxxx-9d71-xxxx-8f20-xxxxxx/tagNames?api-version=2018-05-01";
constructor(private http: HttpClient, private adalSvc: MsAdalAngular6Service) { }
getTags(){
console.log(this.adalSvc.accessToken);
return this.http.get(this.azure_url, this.httpOptions).subscribe(
result => {
console.log(result)
},
error => {
console.log(error)
}
)
}
但是我收到了这个错误:
error="invalid_token", error_description="The access token is from wrong audience or resource.
“
在 AppComponent 中,我可以登录并通过身份验证并接收令牌
constructor(private adalSvc: MsAdalAngular6Service, private ApiService: AzureApiService) {
this.adalSvc.acquireToken('https://management.core.windows.net').subscribe((token: string) => {
console.log(token);
});;
}
但是当我将它作为请求标头中的不记名令牌应用时,它无效。
这是我的 App 模块配置:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { SvgComponent } from './svg/svg.component';
import { DataComponent } from './data/data.component';
import { ListComponent } from './list/list.component';
import { HttpClientModule } from '@angular/common/http';
import { MsAdalAngular6Module, AuthenticationGuard } from 'microsoft-adal-angular6';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SvgComponent,
DataComponent,
ListComponent
],
imports: [
BrowserModule,
HttpClientModule,
MsAdalAngular6Module.forRoot({
tenant: 'xxxxx-a23e-xxxxx-ad14-xxxxxx',
clientId: 'xxxxx-65b0-xxxxx-9425-xxxxxxxxx',
redirectUri: window.location.origin,
authority: 'https://login.microsoftonline.com/common/oauth2/authorize',
endpoints: {
},
navigateToLoginRequestUrl: false,
cacheLocation: 'sessionStorage'
}),
AppRoutingModule
],
providers: [AuthenticationGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
此外,当我转到https://docs.microsoft.com/en-us/rest/api/resources/tags/list并按“试试看”时,我可以在这里登录到我们的 azure 帐户并获得一个工作承载令牌,我们反过来可以在代码中使用它来访问我们想要的资源。