Magento 2 REST API – Fixing 401 Authorization Required Error

catalogmagento2magento2.2productsrest api

I'm trying to get the list of all magento2 products but I'm getting 401 authorization error. I tried the below methods and in all methods I'm getting the mentioned error!

enter image description here

First Method:

$userData = array("username" => "user123", "password" => "pass123");
        $ch = curl_init("http://shop.mysite.com/rest/V1/integration/admin/token");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

        $token = curl_exec($ch);

        $ch = curl_init("http://shop.mysite.com/rest/V1/products");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

        $result = curl_exec($ch);

        $mgtProducts = json_decode($result, 1);

Second Try:

        $consumerKey = 'key';
        $consumerSecret = 'key';
        $accessToken = 'key';
        $accessTokenSecret = 'key';

        $method = 'GET';
        $url = 'http://shop.mysite.com/rest/V1/products';

        $data = array(
            'oauth_consumer_key' => $consumerKey,
            'oauth_nonce' => md5(uniqid(rand(), true)),
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp' => time(),
            'oauth_token' => $accessToken,
            'oauth_version' => '1.0'
        );

        $data['oauth_signature'] = $this->sign($method, $url, $data, $consumerSecret, $accessTokenSecret);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => array(
                'Authorization: OAuth ' . http_build_query($data, '', ',')
            )
        ));

        $result = curl_exec($curl);
        curl_close($curl);

Best Answer

Try the following code

    $domainURL = "http://localhost/magento2.2/index.php";

    $data = array("username" => "<username>", "password" => "<password>");

    $endPoint = '/rest/V1/products?searchCriteria';

    getAPIData($domainURL, $integrationType = 'admin', $data , $endPoint, $showError = false);


    function getAPIData( $domainURL, $integrationType, $data = array(), $endPoint, $showError = false){

        if($integrationType == "admin"){
            $type = '/rest/V1/integration/admin/token';
        }else{
            $type = '/rest/V1/integration/customer/token';
        }

        //API URL for authentication
        $apiURL= $domainURL. $type;

        //parameters passing with URL   
        $data_string = json_encode($data);

        $headers = array("Content-Type: application/json","Content-Length: ".strlen($data_string));

        $token = initCurl( $apiURL, "POST", $headers, $data_string);


        //decoding generated token and saving it in a variable
        $token =  json_decode($token);


        if(!is_object($token)){

            //Using above token into header
            $headers = array('Authorization: Bearer '.$token);

            $requestUrl = $domainURL . $endPoint;

            $method = "GET" ;
            if($integrationType  == "customer"){

                // REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION
                $consumerKey = 'dhxnvui16nrh3nu49f95xkn0oa7y8pm2';
                $consumerSecret = 'cp9qc5s4b44389c4654ffoxwjv4pfysp8a';
                $accessToken = '3d0xeo7926v67867359qs1hkox5b4esxt8wpi';
                $accessTokenSecret = 't4v7o6vxf2sgss351srw98710xkukdyabs';

                $data = [
                    'oauth_consumer_key' => $consumerKey,
                    'oauth_nonce' => md5(uniqid(rand(), true)),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_timestamp' => time(),
                    'oauth_token' => $accessToken,
                    'oauth_version' => '1.0',
                ];

                $data['oauth_signature'] = sign($method, $requestUrl, $data, $consumerSecret, $accessTokenSecret);
                $headers = array('Authorization: OAuth ' . http_build_query($data, '', ','));
            }


            $result = initCurl( $requestUrl, $method, $headers);    

            if($showError){
                var_dump($result);exit;
            }
            //decoding result
            $result=  json_decode($result);
            echo "<pre>";
            //printing result
            print_r($result);       
        } 

    }

    function initCurl( $URL, $method = 'GET', $headers = [], $data_string = ""){

        $ch = curl_init($URL);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        if(!empty($data_string)){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);     
        }

        $response = curl_exec($ch);

        if (curl_error($ch)) {
            $error_msg = curl_error($ch);
            echo $error_msg;
            exit;
        }
        curl_close($ch);

        return $response;
    }

    function sign($method, $url, $data, $consumerSecret, $tokenSecret)
    {
        $url = urlEncodeAsZend($url);

        $data = urlEncodeAsZend(http_build_query($data, '', '&'));
        $data = implode('&', [$method, $url, $data]);

        $secret = implode('&', [$consumerSecret, $tokenSecret]);

        return base64_encode(hash_hmac('sha1', $data, $secret, true));
    }

    function urlEncodeAsZend($value)
    {
        $encoded = rawurlencode($value);
        $encoded = str_replace('%7E', '~', $encoded);
        return $encoded;
    }
Related Topic