Search code examples
phpauthenticationoauth-2.0discordguzzle

Error 401: Unauthorized with Oauth2 for Discord


I am currently developing a connection system through Discord using the Oauth2 API in PHP. For the moment I can get the code to get the access token. I get my access token but I can't get the information about the user who connects because I get this error message :

Client error: `GET https://discord.com/api/oauth2/@me` resulted in a `401 Unauthorized` response:
{ "message": "401: Unauthorized", "code": 0}.

I get the same error message when testing imsomnia with my access token. I use the identify and email scopes. Here is my code maybe it can help you.

I want to specify that the first pages of Google have been looked at without any success...

try{
    $tokenEndpoint='https://discord.com/api/oauth2/token';
    $userinfoEndpoint='https://discord.com/api/oauth2/@me';
    $response=$client->request('POST',$tokenEndpoint,[
        'form_params' => [
        'client_id' => DISCORD_ID,
        'client_secret'=> DISCORD_SECRET,
        'grant_type' => 'authorization_code',
        'code' => $_GET['code'],
        'redirect_uri'=> URL1
        ]
    ]);
    $accessToken=json_decode($response->getBody())->access_token;
    $response=$client->request('GET',$userinfoEndpoint,[
            'headers'=>[
                'Authorization' =>'Bearer' . $accessToken
            ]
        ]);
        $response=json_decode($response->getBody());
        if($response->verified===true)
        {
            //Verifier si util avec openid existe
            //si il n'existe pas insert
            //lancer le reste
            session_start();
            $_SESSION['email']=$response->email;
           
            header('Location: index.php');
            exit();
        }

Thanks in advance for your future answers.


Solution

  • Problem solved

     $response=$client->request('GET',$userinfoEndpoint,[
                    'headers'=>[
                        'Authorization' =>'Bearer '.(string)$accessToken
                    ]
                ]);