首页 > 解决方案 > 在 NestJS 上使用带有 Discord API 的 OAuth2 出现问题

问题描述

我正在尝试为 Discord 创建自定义 API,但现在我正在尝试设置 OAuth2。

为了发出必要的 HTTP 请求,我在 NestJS 中使用了包含的 HttpModule,它是 axios,所以在我的服务中,我定义了一个函数来检索代码(之前由 Discord 发送)并最终获得访问令牌,这是它的外观:

@Injectable()
export class AuthService {
  constructor(private http: HttpService) {}

  async validateToken(token: string) {
    const data = {
      client_id: [some thing],
      client_secret: [some thing],
      grant_type: 'authorization_code',
      code: token,
      redirect_url: encodeURI('https://49fe5ab2.ngrok.io/auth'),
      scope: 'identify',
    };

    return await this.http
      .post('https://discordapp.com/api/oauth2/token', null, { params: data, headers: {"Content-Type": "application/x-www-form-urlencoded"}})
      .toPromise()
      .then(resp => Logger.log(resp))
      .catch(err => Logger.error(err));
  }
}

在控制器中有我为 OAuth2 设置的路由,它只是一个函数

@Controller('auth')
export class AuthController {
  constructor(private readonly AuthService: AuthService) {}

  @Get()
  responseRetrieve(@Req() request) {
      return this.AuthService.validateToken(request.query.code);
  }
}

发生的事情是我只得到 401 状态码,这意味着我的所有访问都是未经授权的。我已经尝试将数据作为请求正文传递,最后将其作为参数传递。

OBS:我知道我应该为客户端 ID 和 client_secret 使用环境变量,但现在我正在尝试完成这项工作。

我没有明白我做错了什么,因为唯一不起作用的是我收到代码后的 axios POST 请求(在服务函数中也称为令牌

标签: node.jsnestjs

解决方案


推荐阅读