401 - Failing call from server, but works in browser

Hello,

when I call from the server the link https://api.twitch.tv/kraken/user?client_id=abcd&authorization=OAuth+rojwncsqlhard627ho1yer41eqj1za it shows an 401 Unauthorized error, however, when I copy & paste the link in my browser I get the wanted result

{"display_name":"zeddyhootrok","_id":124485964,"name":"zeddyhootrok","type":"user","bio":null,"created_at":"2016-05-17T16:15:01Z","updated_at":"2017-12-19T12:40:17Z","logo":"https://static-cdn.jtvnw.net/user-default-pictures/27103734-3cda-44d6-a384-f2ab71e4bb85-profile_image-300x300.jpg","_links":{"self":"https://api.twitch.tv/kraken/users/zeddyhootrok"},"email":"***@***.cz","partnered":false,"notifications":{"push":true,"email":true}}

Error which occures from the server:
Warning: file_get_contents(https://api.twitch.tv/kraken/user?client_id=abcd&authorization=OAuth+rojwncsqlhard627ho1yer41eqj1za) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized in /mnt/web-data1/symbiant_cz/public_html/developer/projects/dgi/ares/aresak.php on line 1106

It is written in Php of course.
I think it doesn’t have some header or something, it’s called from simple file_get_contents tho.
Tell me what causes this, and how to fix this thank you.

The reason as to why it’s working when you’re pasting it in your browser is because you’re logged in to Twitch on your browser. If you were to open an incognito window it would stop working.

You’re setting up your parameters incorrectly though.

Authorization: OAuth -key- is if you’re using a HTTP header.

You want this URL

https://api.twitch.tv/kraken/user?oauth_token=rojwncsqlhard627ho1yer41eqj1za

I would also suggest changing your oauth_token now too, as you’ve just shared it publicly. (Even though you’ve blurred out your email in your paste, it’s viewable from the URL).

1 Like

That seems a long way deep in your program, sure it’s this lookup failing?

Thanks for the full path on your server!

Best kill that oAuth!

Please use cURL.

99.9% of the time file_get_contents performing a HTTP request should fail due to correctly set security settings on the host.

cURL will also allow you to correctly set headers nicely.

For example:

        $curl = curl_init('https://api.twitch.tv/kraken/user');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Accept: application/vnd.twitchtv.v5+json',
            'Authorization: OAuth ' . MYOAUTH
        ));
        $result = curl_exec($curl);
        $i = curl_getinfo($curl);
        curl_close($curl);

        if ($i['http_code'] == 200) {
            $result = json_decode($result);
            // do something with $result
        } else {
            echo 'Failed with a ' . $i['http_code'];
        }

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.