簡體   English   中英

我想獲取我的 Graph API 令牌,但出現錯誤,我正在使用 HttpServices 發出 POST 請求。 我收到 400 狀態碼。 我正在使用 NestJS

[英]I want to get my Graph API token but I got an error, I'm making a POST request with HttpServices. I'm getting a 400 status code. I'm using NestJS

**This is my code when I'm creating the class and the method:**

@Injectable()
export class MicrosoftGraph {
constructor(private httpService: HttpService) {} 
  getMicrosoftGraphToken() {
    const data = {
      client_id: 'myclientid',
      scope: 'https://graph.microsoft.com/.default',
      client_secret: 'myclientsecret',
      grant_type: 'client_credentials'
    }
const url = 
'https://login.microsoftonline.com/mytenantid/oauth2/v2.0/token';
    const response = this.httpService.post(url, data).pipe(
      tap((resp) => console.log(resp)),
      map((resp) => resp.data),
      tap((data) =>  console.log(data)),
    );
    console.log(response);
    return response;
  }
}

這是控制器的一部分:

@Controller('user')
export class UsersController {
  constructor(private readonly microsoftGraph: MicrosoftGraph) {} 
  @Get('hola')
  intento(@Res() res: Response, @Req() req: Request){
    return this.microsoftGraph.getMicrosoftGraphToken();
  }
}

這是我得到的錯誤:

Observable {
  source: Observable {
    source: Observable {
      source: [Observable],
      operator: [Function (anonymous)]
    },
    operator: [Function (anonymous)]
  },
  operator: [Function (anonymous)]
}
[Nest] 19464  - 08/30/2022, 8:05:31 AM   ERROR [ExceptionsHandler] Request failed with status code 400
[Nest] 19464  - 08/30/2022, 8:05:31 AM   ERROR [ExceptionsHandler] undefined

我正在嘗試讓這個令牌能夠實現一個功能,我可以在其中拉出我公司的用戶列表,請幫助並感謝

不確定您是否已經解決了這個問題,但問題出在您的 URL 中。 您已經對 tenantId 部分進行了硬編碼。 所以不是:

 const url = 'https://login.microsoftonline.com/mytenantid/oauth2/v2.0/token';

它可能應該是這樣的:

 const graphTenantId = `1234-abcd-etc-etc`; const url = `https://login.microsoftonline.com/${graphTenantId}/oauth2/v2.0/token`;

您目前的做法是嘗試獲取 ID 為“mytenantid”的租戶。

此外,由於您使用的是 NestJS,我建議您使用 .env 文件來保存您現在放入“數據”常量中的數據,類似於您仍需要添加的 tenant_id。 當然,這僅適用於這些值一成不變的情況。 NestJS 文檔對如何執行此操作有很好的總結。

如果你有關於 Graph API 的動態數據(所以你會有通過你的 NestJS 應用程序連接的客戶端),你最好制作一個 GraphConfiguration 對象,然后你可以使用一個服務(我就是這樣做的)。

希望這對你有幫助!

暫無
暫無

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

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