Linkedin 401 [未授权]令牌错误无效或过期

时间:2014-09-17 07:23:15

标签: php linkedin

我要求使用Linkedin验证我的网站。我使用以下代码来获取linkedin访问令牌。我可以从linkedin文档中看到令牌的有效期为60天。一切都适合我获取访问令牌,我可以看到" expires_in"为5183999秒id(60天)。

我的问题是,当我在2天后使用此令牌请求userinfo时,收到错误401响应。访问令牌的生命周期不稳定。我已经搜索了很多401错误,阅读所以可能链接但没有得到确切的答案。为什么会收到401错误?

请帮我解决这个问题。非常感谢您的帮助。

{ 
        errorCode: 0,
        message: '[unauthorized] Invalid or expired token.',
        requestId: 'P7IR3JY3GZ',
        status: 401,
        timestamp: 1410937984755 
} 

// PHP代码获取访问权限

<?php
    // Change these

    require "config.php";
    //define('API_KEY',     $                                         );
    //define('API_SECRET',   'secret'                                       );
    //define('REDIRECT_URI', 'redirecturl');//http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
    define('SCOPE',        'w_messages rw_company_admin r_fullprofile r_emailaddress rw_nus r_network rw_company_admin rw_groups'                        );



    // You'll probably use a database
    session_name('linkedin');
    session_start();

    // OAuth 2 Control Flow
    if (isset($_GET['error'])) {
        // LinkedIn returned an error
        print $_GET['error'] . ': ' . $_GET['error_description'];
        exit;
    } elseif (isset($_GET['code'])) {
        // User authorized your application
        if ($_SESSION['state'] == $_GET['state']) {
            print_r("ssssssssssssssssssssssssssssssssssssssss");
            // Get token so you can make API calls
            getAccessToken();
        } else {
            // CSRF attack? Or did you mix up your states?
            exit;
        }
    } else { 
        if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
            // Token has expired, clear the state
            $_SESSION = array();
        }
        if (empty($_SESSION['access_token'])) {
            // Start authorization process
            print_r("ddddddddddddddddddddd");
            getAuthorizationCode();
        }
    }

    // Congratulations! You have a valid token. Now fetch your profile 

    $user = fetch('GET', '/v1/people/~:(id,first-name,last-name,picture-url)');
    $pages = fetch2('GET', '/v1/companies:(id,name,logo-url)');

    $user->pages = $pages;
    $user->accesstoken = $_SESSION['access_token'];
    echo "expiry time". $_SESSION['expires_in'];
    print_r($pages);
    print_r($user);

    $SCRIPT = '<script>window.opener.postMessage('.json_encode($user)  .',"*");</script>';
            session_name('linkedin') ;
            session_unset();
            echo $SCRIPT;
            echo '<h1>', HtmlSpecialChars($user->firstName), 
                ' you have logged in successfully with LinkedIn!</h1>';
            echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
    //print "Hello $user->firstName $user->lastName.";
    exit;

    function getAuthorizationCode() {
        $params = array('response_type' => 'code',
                        'client_id' => API_KEY,
                        'scope' => SCOPE,
                        'state' => uniqid('', true), // unique long string
                        'redirect_uri' => REDIRECT_URI,
                  );

        // Authentication request
        $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

        // Needed to identify request when it returns to us
        $_SESSION['state'] = $params['state'];

        // Redirect user to authenticate
        header("Location: $url");
        exit;
    }

    function getAccessToken() {
        $params = array('grant_type' => 'authorization_code',
                        'client_id' => API_KEY,
                        'client_secret' => API_SECRET,
                        'code' => $_GET['code'],
                        'redirect_uri' => REDIRECT_URI,
                  );

        // Access Token request
        $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

        // Tell streams to make a POST request
        $context = stream_context_create(
                        array('http' => 
                            array('method' => 'POST',
                            )
                        )
                    );

        // Retrieve access token information
        $response = file_get_contents($url, false, $context);

        // Native PHP object, please
        $token = json_decode($response);

        // Store access token and expiration time
        $_SESSION['access_token'] = $token->access_token; // guard this! 
        $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
        $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time

        return true;
    }

    function fetch($method, $resource, $body = '') {


        $params = array('oauth2_access_token' => $_SESSION['access_token'],
                        'format' => 'json',
                  );

        // Need to use HTTPS
        $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
        // Tell streams to make a (GET, POST, PUT, or DELETE) request
        $context = stream_context_create(
                        array('http' => 
                            array('method' => $method,
                            )
                        )
                    );


        // Hocus Pocus
        $response = file_get_contents($url, false, $context);



        // Native PHP object, please
        return json_decode($response);
    }

    function fetch2($method, $resource, $body = '') {


        $params = array('is-company-admin'=>'true','format' => 'json','oauth2_access_token' => $_SESSION['access_token'],

                  );

        // Need to use HTTPS
        $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
        // Tell streams to make a (GET, POST, PUT, or DELETE) request
        $context = stream_context_create(
                        array('http' => 
                            array('method' => $method,
                            )
                        )
                    );


        // Hocus Pocus
        $response = file_get_contents($url, false, $context);



        // Native PHP object, please
        return json_decode($response);
    }

0 个答案:

没有答案