【问题标题】: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我想获取我的 Graph API 令牌,但出现错误,我正在使用 HttpServices 发出 POST 请求。我收到 400 状态代码。我正在使用 NestJS
【发布时间】:2022-12-22 02:46:26
【问题描述】:
**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

我正在尝试让这个令牌能够实现一个功能,我可以在其中拉出我公司的用户列表,请帮助并感谢

【问题讨论】:

    标签: javascript node.js typescript microsoft-graph-api nestjs


    【解决方案1】:

    不确定您是否已经解决了这个问题,但问题出在您的 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。当然,这仅适用于这些值一成不变的情况。 The NestJS documentation 对如何做到这一点有很好的总结。

    如果你有关于 Graph API 的动态数据(所以你会有通过你的 NestJS 应用程序连接的客户端),你最好制作一个 GraphConfiguration 对象,然后你可以使用一个服务(我就是这样做的)。

    希望这对你有帮助!

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2020-02-27
      • 2020-04-28
      相关资源
      最近更新 更多