【问题标题】:Invalid redirect_uri in request Discord Oauth2请求 Discord Oauth2 中的 redirect_uri 无效
【发布时间】:2022-03-01 00:05:45
【问题描述】:

我查看了类似我的其他问题,例如this onethis one。但问题是因为使用的 URI 不在 Discord OAuth2 配置中的重定向 URI 中,我检查了好几次。

我有以下代码:

import querySring from 'query-string'

// I'm using React Router for this
const code = searchParams.get('code')

if (!code) return

const data = {
      'client_id': 'my client id',
      'client_secret': 'my client secret',
      'grant_type': 'authorization_code',
      'code': code,
      'redirect_uri': querySring.stringifyUrl({ url: 'http://localhost:3000/login/callback' }),
}

const strData = querySring.stringify(data)   

const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
}

fetch('https://discord.com/api/oauth2/token', {
      method: 'POST',
      headers,
      body: strData,
})
  .then(res => res.json())
  .then(console.log)

我收到以下错误:

error: "invalid_request",
error_description: "Invalid \"redirect_uri\" in request."

当然,我确保在 Discord 开发者门户中有这个重定向 uri:

我也尝试过使用:

const data = {
    // ...
    'redirect_uri': 'http://localhost:3000/login/callback'
}

但没什么,我找不到问题所在。

【问题讨论】:

    标签: javascript oauth-2.0 oauth discord


    【解决方案1】:

    正如空间在Discord API Server 中告诉我的那样,如果我从前端处理登录,我应该使用response_type=token 而不是response_type=code

    那么我可以:

    const token = searchParams.get('access_token')
    const tokenType = searchParams.get('token_type')
    
    /// For some reason the returned url is giving # instead of ? for query
    if (window.location.toString().split('#').length > 1) {
        window.location.replace(window.location.toString().replace('#', '?'))
    }
            
    if (!token || !tokenType) return console.log(`There is no token`)
    
    const headers = {
        authorization: `${tokenType} ${token}`
    }
    

    并使用这些标头获取数据:

    fetch('https://discord.com/api/users/@me', {
        headers,
    })
        .then(res => res.json())
        .then(user=> {
            // ...
         })
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 2016-09-20
      • 2020-10-12
      • 2012-06-08
      • 2020-12-05
      • 2016-12-23
      相关资源
      最近更新 更多