簡體   English   中英

Microsoft graph - 訪問令牌驗證失敗。 無效的觀眾 - 錯誤

[英]Microsoft graph - Access token validation failure. Invalid audience - Error

我正在嘗試使用 Angular 應用程序中的 Graph API 發送郵件。

在 Azure 活動目錄中,我已授予 API Mail.Send 和其他郵件相關內容的權限。

下面是代碼

const resource = {
    grant_type : 'client_credentials',
    clientID: '****************************',
    redirectUri: 'http://localhost:4200/',
    validateAuthority : true,
    popUp: true,
    scopes: ['mail.send'],
    resource : 'https://graph.microsoft.com'
  };

  let murl : any
  murl = 'https://graph.microsoft.com/v1.0/users/' + 'testuser@abcd.onmicrosoft.com' + '/sendMail';

  this.token = await this.msalService.acquireTokenSilent(resource)
      .catch((reason) => {
        // console.log(reason);
      });

      let header = new HttpHeaders({
        'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.token.accessToken});
      let options = { headers: header };

      let resp =  this.http.post(murl, this.sendMailDet, options)
       resp.subscribe(
          (data)=>{
            console.log( data);
        }
        );

但是當我發送郵件時,我得到以下錯誤。

error: {code: "InvalidAuthenticationToken", message: "Access token validation failure. Invalid audience.",…}
code: "InvalidAuthenticationToken"
innerError: {date: "2021-01-06T04:52:20", request-id: "*********",…}
message: "Access token validation failure. Invalid audience."

我在資源中使用范圍:['mail.send'] 仍然收到此錯誤。 我也只使用 this.msalService.acquireTokenSilent(resource) 中的 accessToken。

jwt.ms 中的令牌顯示 aud 為“aud”:“https://graph.microsoft.com”和“scp”:“Directory.Read.All email Mail.Read Mail.Read.Shared Mail.ReadBasic Mail.ReadWrite Mail.ReadWrite.Shared Mail.Send Mail.Send.Shared MailboxSettings.Read MailboxSettings.ReadWrite User.Export.All User.Invite.All User.ManageIdentities.All User.Read User.Read.All User.ReadBasic.All User.ReadWrite User.ReadWrite.All profile openid",

誰能幫我檢查一下這個問題。

我必須從 angular 發送令牌,因為首先會顯示接受或取消彈出窗口。 所以不得不從 angular 處理。 但這給了我問題中提到的錯誤。 所以我為此創建了一個 API 並從 angular 發送他的令牌和其他詳細信息。

這是 Angular 零件

數據: object 帶有 From、To、CC、bcc、emailbody 等。使用這些值,我們創建 json email 格式為 ZDB974A7387143CACE16

async sendmail(data): Promise<Boolean>  
  {

    let result : any ; 
    const resource = {
      clientID: environment.config.identityConfig.clientId , 
      redirectUri: environment.config.identityConfig.redirectUri , // 'http://localhost:4200/'
      validateAuthority : true,
      popUp: true,
      scopes: ['mail.send'],
      resource : 'https://graph.microsoft.com'
    };
    this.token = await this.msalService.acquireTokenSilent(resource)
    .catch((reason) => {
      console.log(reason);
    });

    this.atoken = this.token.accessToken;
    data.EMailAccessToken = this.token.accessToken;
    this.mailHttpService.post('/sendmailgapi', data, null, null, ApiUrl.FileService). // This is custom 
   subscribe((data) => {
     result = data; 
   });

   return result;
  }

然后在 API 中,

this.applicationContext.GetGraphClient():這是另一個使用客戶端 ID、租戶 ID、ClientSecret 並使用 ConfidentialClientApplicationBuilder 的方法,我們創建了一個 Graph 客戶端。

sendMailDto: 傳遞 object

GraphServiceClient graphClient = this.applicationContext.GetGraphClient();
var fromEmail = sendMailDto.EMailFrom ; // 
var accessToken = sendMailDto.EMailAccessToken;
var message = createMessage(sendMailDto);
var restClient = new RestClient("https://graph.microsoft.com/v1.0/users/" + fromEmail + "/sendMail");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + accessToken 
request.AddParameter("", message, ParameterType.RequestBody);
IRestResponse response = restClient.Execute(request);
               

我不確定這是否是正確的方法,但我不得不做一個解決方法來解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM