Giter VIP home page Giter VIP logo

php-oauth2's People

Contributors

adoy avatar aziz-jh avatar bachkoutou avatar bgallagher avatar chrisradford avatar dmp1ce avatar donaldpiret avatar glena avatar jahvi avatar knightar avatar mauris avatar simondotws avatar tamlyn avatar tds89 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-oauth2's Issues

Request Access Token failing..

I'm seeking to access Nimble (CRM)'s API which is a pretty standard OAuth2 process as far as I can tell.

When I request the Authorisation that works fine and I get a login screen and then redirected back to my redirectURI with an appropriate code.

In the next step, requesting the token, I get an error which says: An Authentication object was not found in the SecurityContext

Any idea's? Sorry if this is obvious I'm not well versed in Oauth yet.

Custom Grant Type not Found

I'm attempting to use your library in order to generate an oAuth access token, but I'm experiencing some issues. I got the error:
OAuth2\InvalidArgumentException: Unknown grant type 'my_custom_grant_type' in /Applications/AMPPS/www/whmcs/modules/addons/addonmodule/Client.php:219 Stack trace: #0 /Applications/AMPPS/www/whmcs/modules/addons/addonmodule/addonmodule.php(209): OAuth2\Client->getAccessToken('https://api.san...', 'my_custom_grant...', Array) #1 /Applications/AMPPS/www/whmcs/admin/addonmodules.php(0): addonmodule_sidebar(Array) #2 {main}

When I tried to run:
`
$CLIENT_ID = $vars['id'];
$CLIENT_SECRET = $vars['secret'];

$REDIRECT_URI = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
$AUTHORIZATION_ENDPOINT = 'https://api.sandbox.freeagent.com/v2/approve_app';
$TOKEN_ENDPOINT = 'https://api.sandbox.freeagent.com/v2/token_endpoint';

$client = new OAuth2\Client($CLIENT_ID, $CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl($AUTHORIZATION_ENDPOINT, $REDIRECT_URI);
echo('<script>window.location="'.$auth_url.'";</script>');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => $REDIRECT_URI);
$response = $client->getAccessToken($TOKEN_ENDPOINT, 'my_custom_grant_type', $params);
var_dump($response);
parse_str($response['result'], $info);
$client->setAccessToken($info['access_token']);
$response = $client->fetch('https://api.freeagent.com/v2/contacts');
}`

I've also included the example custom grant type inside a file placed after the the IGrantType.php, and included the file, using include(''), inside the main php file, and yet I'm still getting the same issue.

Add curl timeout parameter ?

Hello,

It's possible to add something to change the curl timeout and connect timeout ? (CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT)

If you are interested, I can make a pull request to add the curl timeout support.

How to send JSON post body data

Hi,

I'm trying to make an OAuth request using raw JSON data as post body but am having trouble figuring out how to do that since your fetch method requires the parameters to be an array.
Could you enlighten me on how this would work?

Usage of other grant types unclear?

Maybe this just requires a little more documentation, or maybe it's just because I'm new to using OAuth2, but it was unclear to me until digging through the Client.php file and checking on a bunch of outputs that in order to switch over to Client Credentials from Authorization Code, one has to add a third parameter to the client instantiation:

$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET, 1);

I'm assuming that is the proper way to go about it, but please correct me if I'm wrong.

401 Unauthorized even if all necessary tokens passed as params

@adoy
@bachkoutou

<?php
require_once('Client.php');
require_once('Logging.php');
require_once('GrantType/IGrantType.php');
autoLoadAll();

const CLIENT_ID = '<client_id>';
const CLIENT_SECRET = '<client_secret>';
const REDIRECT_URI = 'https://webexpressen.no/oauth2/';
const AUTHORIZATION_ENDPOINT = 'https://auth-sandbox.test.vismaonline.com/eaccountingapi/oauth/authorize';
const TOKEN_ENDPOINT = 'https://auth-sandbox.test.vismaonline.com/eaccountingapi/oauth/token';

$log = new Logging();
#set path and name of log file (optional)
$log->lfile($_SERVER["DOCUMENT_ROOT"].'/oauth2/customPhp.log');
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if(!isset($_GET['code']))
{
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
    $log->lwrite("\nAUTH_URL:".$auth_url);
    header('Location: ' . $auth_url);
    die('Redirect');
}
else
{
    session_start();
    $params = array('code' => $_REQUEST['code'], 'redirect_uri' => REDIRECT_URI);
    $_SESSION['params'] = $params;
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $_SESSION['params']);
    $log->lwrite(print_r($response, true));
    $client->setAccessToken($response['result']['access_token']);

    $_SESSION['params']['refresh_token'] = $response['result']['refresh_token'];
    $_SESSION['headers']['client_id'] = CLIENT_ID;
    $_SESSION['headers']['client_secret'] = CLIENT_SECRET;
    $_SESSION['headers']['scope'] = "accounting+accounting_readonly";
    $_SESSION['headers']['redirect_uri'] = REDIRECT_URI;
    $_SESSION['headers']['refresh_token'] = $response['result']['refresh_token'];

    $atResponse = $client->getAccessToken(TOKEN_ENDPOINT, 'refresh_token', $_SESSION['headers']);
    //Get the data from given external resource by `fetch` method of Client.php
    $_SESSION['params']['includeZeroBalance'] = true;
    echo "<pre/>All session values";print_r($_SESSION);
    $dataEndpoint = "https://eaccountingapi-sandbox.test.vismaonline.com/v1/accountbalances/2016-01-15";
    $accountData = $client->fetch($dataEndpoint, $_SESSION['params'], 'GET', $_SESSION['headers']);
    echo "<pre/>Account Data:";print_r($accountData);
}
// close log file
$log->lclose();

function autoLoadAll() {
    $scan = scandir('GrantType/');
    foreach ($scan as $class) {
        if (strpos($class, '.php') !== false && strpos($class, 'IGrantType') === false) {
            require_once('GrantType/' . $class);
            #include_once('GrantType/' . $class);
        }
    }
    return true;
}

Please look at the above script I have built for calling an external api by passing through Oauth2 Authentication Mechanism using your Client Library.

As you can see I have passed all necessary tokens and parameters properly in standard format but still when I run the given script I get below message:

Array
(
    [result] => Array
        (
            [Message] => Unauthorized
        )

    [code] => 401
    [content_type] => application/json; charset=utf-8
)

Below is a reference link about webservice documentation.
https://developer.vismaonline.com/ - I am calling the very first webservice /v1/accountbalances/{date}

Can someone assist me about what could be wrong, I can disclose only this much code.

Waiting....

How to make it work with Facebook and Microsoft Live

Hi all,

Great script, thanks a lot! And with only a few alterations I got it to work with Microsoft Live as well. I'am fairly new to github and versioning, so instead of a patch file just a few pointers:

  • getAccessToken() returns an object with self::HTTP_METHOD_POST. MS seems not to like POST requests, FB likes both POST and GET, so changing it to self::HTTP_METHOD_GET gets the expected result for both providers,
  • executeRequest() returns the json_decode'd result, but MS returns a querystring instead of a JSON string. So I changed
return array(
  'result' => json_decode($result),
  'code' => $http_code,
  'content_type' => $content_type
);

into

if (preg_match('#^\s*{\s*[\'"]#' , $result)) {
  $params=json_decode($result);
}
else {
  parse_str($result, $params);
}

return array(
  'result' => (object) $params,
  'code' => $http_code,
  'content_type' => $content_type
);

Now the script checks if the resulted string looks like a JSON string or regular querystring, parses it into an array and returns the array as an object for backwards compatibility. Maybe you have a better solution for it, but it works fine for me!

Laurens Meurs (Rotterdam, The Netherlands)

Fatal Error When Using bshaffer/oauth2-server-php 1.7 and above

Recently updated my project through composer and OAuth2 started failing when requesting the access token.

Here's the code:
$tokeninfo = $client->getAccessToken($this->BASE_URL . $this->TOKEN_URL, 'authorization_code', array('code' => $code,'redirect_uri' => SITE_URL . "/externallogin/" . $this->organization_id));

Here's the error:
PHP Catchable fatal error: Argument 1 passed to OAuth2\GrantType\AuthorizationCode::__construct() must be an instance of OAuth2\Storage\AuthorizationCodeInterface, none given, called in vendor/adoy/oauth2/src/OAuth2/Client.php on line 220 and defined in vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/AuthorizationCode.php on line 22

Downgrading to version 1.6 fixes the issue.

Insecure curl / https usage

The library appears to explicitly disable curl's SSL peer/host checks when a certificate file is not provided in executeRequest:

        // https handling
        if (!empty($this->certificate_file)) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, $this->certificate_file);
        } else {
            // bypass ssl verification
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        }

This is insecure as it opens the user to a MITM attack and negates the point of using SSL. By default if CURLOPT_CAINFO is not set, curl uses the system CA bundle to verify certificates, so enabling the host and peer verification only when a manual certificate file is specified is incorrect and reduces security.

How to refresh token in Reddit Api with basic auth?

I am using you library for performing authentication on reddit and posting on reddit but i can't refresh the token using your library.

To refresh token i use the following code, using this library (https://github.com/php-curl-class/php-curl-class)

 $accessTokenUrl = 'https://ssl.reddit.com/api/v1/access_token';
    $clientId = 'ClientID';
    $clientSecret = 'ClientSecret';
    $redirectUrl = "YourURL";

    $string = $clientId.":".$clientSecret;
    $val = base64_encode($string);
    $val = " Basic ".$val;

    $curl = new Curl();
    $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE);
    $curl->setOpt(CURLOPT_SSL_VERIFYPEER, FALSE);

    $curl->setHeader('Authorization', $val);

    $curl->post($accessTokenUrl, array(
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'grant_type' => 'refresh_token',
        'refresh_token' => $refresh_token,
        'scope' => 'identity,edit,submit',
        'state' => 'refresh_token',
        'duration' => 'permanent',
        'redirect_uri' => $redirectUrl
    ));
    if (!$curl->error) {
        if ($curl->http_status_code == 200){
            $resp_data = json_decode($curl->response, 1);
            $data = array('error' => 0, 'data' => $resp_data);
            return $data;
        }else{
            $data = array('error' => 1);
            return $data;
        }
    }else{
        $data = array('error' => 1);
        return $data;
    }

Note: the api requires a Basic auth with client id as username and client secret as password.

It would be really great if you can help me implement refresh token with this library.

Issue with POST json data

Hi

I am using the snippet code below for POST an new event, but failed with 400 Error. just wondering if I missed something or can you please provide me the sample code of POST data?

My email address is: [email protected]

setAccessTokenType(2,$client->getClientSecret()); $param ='{"event":{"name":"ACF API Test","intro":"protect our environment","start_time":"2016-02-08T17:00:00-00:00","end_time":"2016-02-08T19:00:00-00:00","status":"unlisted"}}'; $response = $client->fetch($this->nb_baseapiUrl . '/api/v1/events/', $param, 'POST'); print_r($response); ?>

Regards
Stanley

Simple Request

Hello

Can anyone please share the syntax for using the fetch call with a bearer token?

Thanks

handshake failure

I dont know if this helps, but without adding this options in #L407 will throwed "SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure' in /OAuth2/Client.php:473"

$curl_options = array(
  //CURLOPT_SSLVERSION => 3,
  //CURLOPT_SSL_CIPHER_LIST => 'SSLv3',
  CURLOPT_SSL_CIPHER_LIST => 'RC4-SHA',
  CURLOPT_SSL_CIPHER_LIST => 'TLSv1',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_SSL_VERIFYPEER => true,
  CURLOPT_CUSTOMREQUEST  => $http_method
);

POST data

request body for post data is not working

Could you change the file name to match the class name?

The autoload in frameworks such as Symfony2 expects that the file name matches the class name contained within, and in its current state the autoload can't find the class this way. That's because of the case sensitivity of some file systems. So, would you be able to change the name of "client.php" to "Client.php" since that's what the class is named?

Planned new release?

Hi,

When do you plan to bump a new version?
We need the changes done in the commits done the 3rd of July by @glena.

Until the new version is released in his library he's using the "dev-master" branch of your library in their dependencies.

Update tag

Please update release tag so that composer can get the latest version. I have to do adoy/oauth2: dev/master right now

How to use the refresh token

I have made the setup for php-oauth2 with wordpress. But it get expires after some days. I want to stay it permanent or use the refresh token to renew the token automatically using php code. Please can you help me.

unexpected T_CONST ?

Hi there,

I'm struggling to get past the basic example provided in the docs.

I'm just getting the following error on execution:

PHP Parse error: syntax error, unexpected T_CONST

On the first instance of a constant, in this case:

const CLIENT_ID = 'redacted';

After 10 minutes of Googling the only reference I can find to this issue is due to using PHP4, but I'm running 5.3.6. I'm running this code from within a codeigniter controller, I'm not sure if this is in any way relevent, perhaps it's a scope thing? Full code looks a little more like:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Prop extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    public function testoauth()
    {

        require( site_url('oauth/client.php') );
        require( site_url('oauth/GrantType/IGrantType.php') );
        require( site_url('oauth/GrantType/AuthorizationCode.php') );

        const CLIENT_ID     = 'redacted';
                ...

Any ideas?

Create a version release

Hi!, could you create a release so we can add the project to our library and avoid the composer minimum stability problem?

Thanks

How to POST json data

Hi,

In this closed issue (#6) I see that it is possible to post JSON data. I can't seem to get it to work. I'm not a PHP expert so I could be missing something basic.

my code
$data = '{"action": "read"}';
$response = $client->fetch('https://the-api-resource', $data, 'POST');

I keep getting a "Authentication parameters missing" message from the server so I thought I might not have a proper access token but a var_dump of $client looks ok to me...

object(OAuth2\Client)#3 (10) { ["client_id":protected]=> string(8) "7c23519f" ["client_secret":protected]=> string(32) "6e71a3a1452f4ee1df71771192dbc526" ["client_auth":protected]=> int(0) ["access_token":protected]=> string(40) "c88eeaea6cf10ec207edfe0f0fc2e27d55f1cc29" ["access_token_type":protected]=> int(0) ["access_token_secret":protected]=> NULL ["access_token_algorithm":protected]=> NULL ["access_token_param_name":protected]=> string(12) "access_token" ["certificate_file":protected]=> NULL ["curl_options":protected]=> array(0) { } }

Thanks

parse_str() expects parameter 1 to be string

The "parse_str($response['result'], $info);" as shown in "How can I use it?" gives me the error

Warning: parse_str() expects parameter 1 to be string, array given in /home/u490548713/public_html/auth.php on line 27

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.