Search code examples
javascriptoauth-2.0oauthdiscord

Invalid redirect_uri in request Discord Oauth2


I looked at other problems like mine, for example this one or this one. But the problems are because the URIs used aren't in the Redirect URIs in Discord OAuth2 config, and I checked them several times.

I have the following code:

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)

And I get the following error:

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

Of course, I made sure of having this redirect uri in the Discord Developer Portal: Redirect urls config

I also tried using:

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

But nothing, I can't find what is wrong.


Solution

  • As space told me in the Discord API Server, if I'm handling the login from the frontend I should use response_type=token instead of response_type=code

    So then I can:

    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}`
    }
    

    And use these headers for fetching data:

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