Git Product home page Git Product logo

oauth1-client's Introduction

OAuth 1.0 Client

Latest Stable Version Software License Build Status Coverage Status Quality Score Total Downloads

OAuth 1 Client is an OAuth RFC 5849 standards-compliant library for authenticating against OAuth 1 servers.

It has built in support for:

  • Bitbucket
  • Magento
  • Trello
  • Tumblr
  • Twitter
  • Uservoice
  • Xing

Adding support for other providers is trivial. The library requires PHP 7.1+ and is PSR-2 compatible.

Third-Party Providers

If you would like to support other providers, please make them available as a Composer package, then link to them below.

These providers allow integration with other providers not supported by oauth1-client. They may require an older version so please help them out with a pull request if you notice this.

Terminology (as per the RFC 5849 specification):

client
    An HTTP client (per [RFC2616]) capable of making OAuth-
    authenticated requests (Section 3).

server
    An HTTP server (per [RFC2616]) capable of accepting OAuth-
    authenticated requests (Section 3).

protected resource
    An access-restricted resource that can be obtained from the
    server using an OAuth-authenticated request (Section 3).

resource owner
    An entity capable of accessing and controlling protected
    resources by using credentials to authenticate with the server.

credentials
    Credentials are a pair of a unique identifier and a matching
    shared secret.  OAuth defines three classes of credentials:
    client, temporary, and token, used to identify and authenticate
    the client making the request, the authorization request, and
    the access grant, respectively.

token
    A unique identifier issued by the server and used by the client
    to associate authenticated requests with the resource owner
    whose authorization is requested or has been obtained by the
    client.  Tokens have a matching shared-secret that is used by
    the client to establish its ownership of the token, and its
    authority to represent the resource owner.

The original community specification used a somewhat different
terminology that maps to this specifications as follows (original
community terms provided on left):

Consumer:  client

Service Provider:  server

User:  resource owner

Consumer Key and Secret:  client credentials

Request Token and Secret:  temporary credentials

Access Token and Secret:  token credentials

Install

Via Composer

$ composer require league/oauth1-client

Usage

Bitbucket

$server = new League\OAuth1\Client\Server\Bitbucket([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => "http://your-callback-uri/",
]);

Trello

$server =  new League\OAuth1\Client\Server\Trello([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => 'http://your-callback-uri/',
    'name' => 'your-application-name', // optional, defaults to null
    'expiration' => 'your-application-expiration', // optional ('never', '1day', '2days'), defaults to '1day'
    'scope' => 'your-application-scope' // optional ('read', 'read,write'), defaults to 'read'
]);

Tumblr

$server = new League\OAuth1\Client\Server\Tumblr([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => "http://your-callback-uri/",
]);

Twitter

$server = new League\OAuth1\Client\Server\Twitter([
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => "http://your-callback-uri/",
    'scope' => 'your-application-scope' // optional ('read', 'write'), empty by default
]);

Xing

$server = new League\OAuth1\Client\Server\Xing([
    'identifier' => 'your-consumer-key',
    'secret' => 'your-consumer-secret',
    'callback_uri' => "http://your-callback-uri/",
]);

Showing a Login Button

To begin, it's advisable that you include a login button on your website. Most servers (Twitter, Tumblr etc) have resources available for making buttons that are familiar to users. Some servers actually require you use their buttons as part of their terms.

<a href="authenticate.php">Login With Twitter</a>

Retrieving Temporary Credentials

The first step to authenticating with OAuth 1 is to retrieve temporary credentials. These have been referred to as request tokens in earlier versions of OAuth 1.

To do this, we'll retrieve and store temporary credentials in the session, and redirect the user to the server:

// Retrieve temporary credentials
$temporaryCredentials = $server->getTemporaryCredentials();

// Store credentials in the session, we'll need them later
$_SESSION['temporary_credentials'] = serialize($temporaryCredentials);
session_write_close();

// Second part of OAuth 1.0 authentication is to redirect the
// resource owner to the login screen on the server.
$server->authorize($temporaryCredentials);

The user will be redirected to the familiar login screen on the server, where they will login to their account and authorise your app to access their data.

Retrieving Token Credentials

Once the user has authenticated (or denied) your application, they will be redirected to the callback_uri which you specified when creating the server.

Note, some servers (such as Twitter) require that the callback URI you specify when authenticating matches what you registered with their app. This is to stop a potential third party impersonating you. This is actually part of the protocol however some servers choose to ignore this.

Because of this, we actually require you specify a callback URI for all servers, regardless of whether the server requires it or not. This is good practice.

You'll need to handle when the user is redirected back. This will involve retrieving token credentials, which you may then use to make calls to the server on behalf of the user. These have been referred to as access tokens in earlier versions of OAuth 1.

if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
    // Retrieve the temporary credentials we saved before
    $temporaryCredentials = unserialize($_SESSION['temporary_credentials']);

    // We will now retrieve token credentials from the server
    $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
}

Now, you may choose to do what you need with the token credentials. You may store them in a database, in the session, or use them as one-off and then forget about them.

All credentials, (client credentials, temporary credentials and token credentials) all implement League\OAuth1\Client\Credentials\CredentialsInterface and have two sets of setters and getters exposed:

var_dump($tokenCredentials->getIdentifier());
var_dump($tokenCredentials->getSecret());

In earlier versions of OAuth 1, the token credentials identifier and token credentials secret were referred to as access token and access token secret. Don't be scared by the new terminology here - they are the same. This package is using the exact terminology in the RFC 5849 OAuth 1 standard.

Twitter will send back an error message in the denied query string parameter, allowing you to provide feedback. Some servers do not send back an error message, but rather do not provide the successful oauth_token and oauth_verifier parameters.

Accessing User Information

Now you have token credentials stored somewhere, you may use them to make calls against the server, as an authenticated user.

While this package is not intended to be a wrapper for every server's API, it does include basic methods that you may use to retrieve limited information. An example of where this may be useful is if you are using social logins, you only need limited information to confirm who the user is.

The four exposed methods are:

// User is an instance of League\OAuth1\Client\Server\User
$user = $server->getUserDetails($tokenCredentials);

// UID is a string / integer unique representation of the user
$uid = $server->getUserUid($tokenCredentials);

// Email is either a string or null (as some providers do not supply this data)
$email = $server->getUserEmail($tokenCredentials);

// Screen name is also known as a username (Twitter handle etc)
$screenName = $server->getUserScreenName($tokenCredentials);

League\OAuth1\Client\Server\User exposes a number of default public properties and also stores any additional data in an extra array - $user->extra. You may also iterate over a user's properties as if it was an array, foreach ($user as $key => $value).

Examples

Examples may be found under the resources/examples directory, which take the usage instructions here and go into a bit more depth. They are working examples that would only you substitute in your client credentials to have working.

Testing

$ phpunit

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

oauth1-client's People

Contributors

adamwathan avatar arcanedev-maroc avatar assertchris avatar bencorlett avatar bhupendra-mp avatar cossou avatar craig-davis avatar cyk avatar driesvints avatar frankdejonge avatar gelembjuk avatar grahamcampbell avatar guss77 avatar jtsternberg avatar kleiram avatar monsieurmechant avatar patrickkusebauch avatar pborreli avatar pendexgabo avatar prisis avatar shadowhand avatar sitesense avatar smares avatar stevenmaguire avatar unreal4u avatar vovayatsyuk avatar vpx avatar y0lk 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

oauth1-client's Issues

Last release is broken

Hey,
I made a pull request last week about Twitter, but I don't test it because I thought the Twitter docs were clear enough.
Sadly, it was not.
So now, when we make an oauth connection with Twitter, we get this :

{
    "errors":[{
        "code":32,
        "message":"Could not authenticate you."
    }]
}".

This error is documented here : https://developer.twitter.com/en/support/twitter-api/error-troubleshooting (search for "code 32" in the page).
I haven't already find a solution to fix that, but I will made a PR a soon as possible.

Sorry for that.

user-agent

is there a way to set a user-agent in the requests?

Trello "An unknown application"

Calling the class with parameter name don't seems to apply it to Trello.

$Trello = new Trello([
            'identifier' => c('TRELLO_KEY'),
            'secret' => c('TRELLO_SECRET'),
            'callback_uri' => Http::url(),
            'name' => c('APP_NAME'),
            'expiration' => 'never',
            'scope' => 'read,write'
        ]);

The value of APP_NAME get passed in the URL, but the result on the Trello auth-page is "An unknown application" instead of the expected value.

OAuth_token is not equal to temporary_credentials->getIdentifier(), causing MITM warning

https://github.com/thephpleague/oauth1-client/blob/master/src/Client/Server/Server.php#L150

I extended Server for a different provider (SocialFlow.php file below), and after the auth redirect, I am given an OAuth_token, which I store in $_SESSION.

I also serialize and store the temporary_credentials the same way.

Then, I initialize it again, with the signature, for an endpoint run:

$server = new SocialFlow($args->client_credentials, unserialize($args->signature));
        try {
            $token = $server->getTokenCredentials(unserialize($args->temporary_credentials), $args->token_credentials['oauth_token'], $args->token_credentials['oauth_verifier']);
            return $server->getAccountsList($token);
        }...

The crux of the issue: the temporary_credentials that are given to me from SocialFlow don't have the same ID as the OAuth_token given to me after the auth redirect.

And I still get the warning Temporary identifier passed back by server does not match that of stored temporary credentials. .

What am I doing wrong?


SocialFlow extends Server.php


namespace ...;

use League\OAuth1\Client\Credentials\TokenCredentials;
use League\OAuth1\Client\Server\Server;

class SocialFlow extends Server
{
    /**
     * {@inheritDoc}
     */
    public function urlTemporaryCredentials()
    {
        return 'https://www.socialflow.com/oauth/request_token';
    }

    /**
     * {@inheritDoc}
     */
    public function urlAuthorization()
    {
        return 'https://www.socialflow.com/oauth/authorize';
    }

    /**
     * {@inheritDoc}
     */
    public function urlTokenCredentials()
    {
        return 'https://www.socialflow.com/oauth/access_token';
    }

    /**
     * {@inheritDoc}
     */
    public function urlUserDetails()
    {
        return 'https://api.socialflow.com/account/list';
    }

    /**
     * {@inheritDoc}
     */
    public function userDetails($data, TokenCredentials $tokenCredentials)
    {
        return $data; //todo
    }

    /**
     * {@inheritDoc}
     */
    public function userUid($data, TokenCredentials $tokenCredentials)
    {
        return $data['id']; //todo
    }

    /**
     * {@inheritDoc}
     */
    public function userEmail($data, TokenCredentials $tokenCredentials)
    {
        return; //todo
    }

    /**
     * {@inheritDoc}
     */
    public function userScreenName($data, TokenCredentials $tokenCredentials)
    {
        return $data['name']; //todo
    }

    /**
     * Generic GET call using authorized credentials and specified path
     *
     * @param TokenCredentials $tokenCredentials
     * @param String $url
     *
     * @return array HTTP client response
     */
    protected function genericGetCall(TokenCredentials $tokenCredentials, $url)
    {
        $client = $this->createHttpClient();

        $headers = $this->getHeaders($tokenCredentials, 'GET', $url);
        print_r($headers);
        try {
            $response = $client->get($url, [
                'headers' => $headers,
            ]);
        } catch (BadResponseException $e) {
            $response = $e->getResponse();
            $body = $response->getBody();
            $statusCode = $response->getStatusCode();

            throw new \Exception(
                "Received error [$body] with status code [$statusCode] when retrieving token credentials."
            );
        }
        switch ($this->responseType) {
            case 'json':
                return json_decode((string) $response->getBody(), true);
                break;

            case 'xml':
                return simplexml_load_string((string) $response->getBody());
                break;

            case 'string':
                return [$response->getBody()];
                break;

            default:
                throw new \InvalidArgumentException("Invalid response type [{$this->responseType}].");
        }
    }

    public function getAccountsList(TokenCredentials $tokenCredentials)
    {
        return $this->genericGetCall($tokenCredentials, 'https://api.socialflow.com/account/list');
    }
}

Salesforce integration

Hello

Will this allow me to create an OAuth connection to Salesforce? I want to send two REST calls from Wordpress:

  1. When a new user is created, REST PUT to create a contact in Salesforce, updating the Wordpress user with the Salesforce ID generated

  2. When the user profile is updated, REST PATCH to update the contact in Salesforce using the ID

This would be fantastic, would be happy to donate if this can be made to work.

Robin

No accept header

The default server headers assume the API will provide either JSON or XML but never explicitly require it. This means that switching the accept type with an API like intuit which currently always returns XML for user info, creates an error.

Server.php on line 355

355 |    protected function getHttpClientDefaultHeaders()
356 |    {
357 |        $defaultHeaders = array();
358 |        if (!empty($this->userAgent)) {
359 |            $defaultHeaders['User-Agent'] = $this->userAgent;
359 |        }
360 |
361 |        return $defaultHeaders;
362 |    }

I'm Recommending:

355 |    protected function getHttpClientDefaultHeaders()
356 |    {
357 |        $defaultHeaders = array();
358 |        if (!empty($this->userAgent)) {
359 |            $defaultHeaders['User-Agent'] = $this->userAgent;
359 |        }
360 |        $defaultHeaders['Accept'] = 'application/'. $this->responseType;
361 |
362 |        return $defaultHeaders;
363 |    }

Not sure if I am being pedantic but I figure an application probably shouldn't assume an encoding type unless it's requested it in the first place?

I'm extending this repo to build an entire quickbooks api subscriber and I want to switch from xml to json as soon as I have the user info.

[Proposal] Allow to send arbitrary requests

As Laravel is using this package underneath Socialite, I thought I might as well keep using it for interacting with an OAuth server (that of Twitter, but more are on the roadmap) after authenticating. So what I did is the following:

  • I am using Laravel 5 its default implementation of Socialite

  • After authenticating, I save the User its token and tokenSecret (Twitter is OAuth 1)

  • Because the default server implementation for Twitter in this package does not leverage any functionality beyond authenticating, I extended the Server\Twitter class

  • Created a method for retrieving the statuses/update resource URL as already demonstrated in the base class, very straight forward:

    class Twitter extends \League\OAuth1\Client\Server\Twitter
    {
    
        public function urlStatusUpdate()
        {
            return 'https://api.twitter.com/1.1/statuses/update.json';
        }
    
        // ...
    
  • Created a method for sending a Tweet. I copied all the code from Server\Server->fetchUserDetails() to my extended Twitter class (see above) its postStatusUpdate method and made the following changes:

    • $url = $this->urlStatusUpdate();
    • $header = $this->protocolHeader('POST', $url, $tokenCredentials); (POST instead of GET)
    • $response = $client->post($url, $headers, $postBody)->send(); (->post instead of ->get and appended $postBody which is an argument of postStatusUpdate (for setting the status body param, see below))
  • The server is tested as follows

    $credentials = new TokenCredentials();
    $credentials->setIdentifier($this->auth->getUser()->oauth_token);
    $credentials->setSecret($this->auth->getUser()->oauth_token_secret);
    
    $twitterServer = new Twitter($twitterConfig);
    dd($twitterServer->postStatusUpdate($credentials, ['status' => 'test']));
    
  • where the oath_token and oauth_token_secret were earlier saved

However, I get a Authorization Required status response from Twitter. Upon dumping the headers of the internal Guzzle client, all required authorization headers are properly set. My Twitter application has the correct amount of permissions (read & write) to write to the statuses/update resource.

  • Am I missing something obvious?
  • Is there an easier way to do this? (other OAuth requests than those already defined in the package)
  • Is this library even intended to be extended in such a way that requests can be made beyond authorization?

Thanks in advance.

Clean way for forcing oauth_verifier to be in Auth header

I'm using thephpleague/oauth1-client with an OAuth1 server which will only work if the oauth_verifier is present in the header instead of as a body parameter which is how it currently is implemented.

In order to get around this limitation and have this client work I implemented the following method in my Server file.

    /**
     * {@inheritDoc}
     */
    protected function protocolHeader($method, $uri, CredentialsInterface $credentials, array $bodyParameters = array())
    {
        $parameters = array_merge(
            $this->baseProtocolParameters(),
            $this->additionalProtocolParameters(),
            array(
                'oauth_token' => $credentials->getIdentifier(),
            )
        );

        /**
         * BEGIN: Modification to parent::protocolHeader()
         * Note: THE API will not accept oauth_verifier as a body parameter. It must be in the OAuth Authorization
         * header
         */
        if (isset($bodyParameters['oauth_verifier'])) {
            $parameters['oauth_verifier'] = $bodyParameters['oauth_verifier'];
            unset($bodyParameters['oauth_verifier']);
        }
        /**
         * END: Modification to parent::protocolHeader()
         */

        $this->signature->setCredentials($credentials);

        $parameters['oauth_signature'] = $this->signature->sign(
            $uri,
            array_merge($parameters, $bodyParameters),
            $method
        );

        return $this->normalizeProtocolParameters($parameters);
    }

I'm not enthused about this solution and was looking to see if there was a more elegant solution.

Note: With a little bit of a research I don't believe the spec states that it should or shouldn't be in the header or the body; however, some have stated that it makes more sense to have it in the header with the rest of the oauth_parameters.

Add email to Twitter

Since April of this year Twitter is now able to supply a user's email address, with one caveat - you need to have your app whitelisted. See the post by andypiper of Twitter here:

https://twittercommunity.com/t/how-to-get-email-from-twitter-user-using-oauthtokens/558/185

I got this to work by making a few minor changes to src/Client/Server/Twitter.php - look for CHANGED...

I haven't made a PR because I think you guys will probably have better ideas on how to implement it.

public function urlUserDetails()
    {
        // return 'https://api.twitter.com/1.1/account/verify_credentials.json';
        // CHANGED added querystring
        return 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true';
    }

    /**
     * {@inheritDoc}
     */
    public function userDetails($data, TokenCredentials $tokenCredentials)
    {
        $user = new User();

        $user->uid = $data['id'];
        $user->nickname = $data['screen_name'];
        $user->name = $data['name'];

        // CHANGED added email
        $user->email = null;
        if (isset($data['email'])) {
            $user->email = $data['email'];
        }

        $user->location = $data['location'];
        $user->description = $data['description'];
        $user->imageUrl = $data['profile_image_url'];

        // CHANGED added email
        //$used = array('id', 'screen_name', 'name', 'location', 'description', 'profile_image_url');
        $used = array('id', 'screen_name', 'name', 'email', 'location', 'description', 'profile_image_url');

        foreach ($data as $key => $value) {
            if (strpos($key, 'url') !== false) {
                if (!in_array($key, $used)) {
                    $used[] = $key;
                }

                $user->urls[$key] = $value;
            }
        }

        // Save all extra data
        $user->extra = array_diff_key($data, array_flip($used));

        return $user;
    }

Build failing on travis

There seems to be some sort of issue with use of Mockery in the build, the tests were passing prior to the last commit. I'm going to dig around a little bit and see if I can't get the travis build to pass. I'm using this as an example in my book, I'd just feel better about doing so if I could see the tests pass. Cheers!

Common interface with OAuth2-client

Hello,

First, your two lib OAuth1 & 2 are awesome: that's exactly what I'm looking for : simple, clear & clean (after struggling with the HWIOAuthBundle, it's a big change).

I need both library in my app (for twitter & facebook authentication) so: is there a plan to unify or at least create some common interfaces between the two lib because OAuth2..\AbstractProvider and OAuth1...\Server for example have a lot of common behaviors ?

Is it a good idea ? Is it even possible ? Is it planned ? I understand that Twitter will someday change to OAuth2 so it's not a priority.

Today I'm working on a Bridge pattern for encapsulating each Provider. In this way my security layer (in symfony2) will deal with only one type of object.

Anyway, thanks for your opinion.

Upgrade to a current version of guzzle

Right now this repository depends on an outdated version of guzzle. This version will be EOL later this year and ideally should be repalced with the more current guzzlehttp.

Twitter not redirecting to the good url ?

Hi,
Using a configuration of this type, the oauth1-client works, but for some reason, Twitter redirects my to my domain name only, and not my full url. Any idea if it comes from the library or twitter or me ?

$server = new League\OAuth1\Client\Server\Twitter(array(
'identifier' => 'XXXX',
'secret' => 'XXXX',
'callback_uri' => 'http://debian-machine.com/API/oAuth/Twitter'
));

Avoid "functions" from dependencies

Guzzle has deprecated the use of functions provided by their dependencies (as you can see here) in their latest versions.
I think it might make sense to upgrade the use of them in oauth1-client too, for example in EncodesUrl.php:

protected function createUrl($uri)
{
    return Psr7\uri_for($uri);
}

Becomes:

protected function createUrl($uri)
{
    return Psr7\Utils::uriFor($uri);
}

This will make the library future proof of any deprecation (and eventually give us the ability to use Mozart on it, as at the moment it will crash on those function calls).

Twitter could not authenticate temporary credentials

I've used the twitter example in the repo and getting this error. The error also comes from this line.

I am able to get temporary credentials and able to get oauth token, but when I do use the returned token to fetch user details, I'm unable to fetch it thus the error.

League\OAuth1\Client\Credentials\CredentialsException: Received HTTP status code [401] with message "{"errors":[{"code":32,"message":"Could not authenticate you."}]}" when getting temporary credentials. in /vendor/league/oauth1-client/src/Client/Server/Server.php:418

I read an issue like this and they are referring to setting isSecure: false but I'm unable to find this in the package. Could you please help me. Thanks

Invalid auth/bad request Etsy

Anyone else getting this?

Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)

Notice: Undefined variable: acc_token in /home/user****/**nd/test.php on line 30

Multidimensional arrays

When sending multidimensional array data through the client, you will get this error:

rawurlencode() expects parameter 1 to be string, array given

Is this a bug, or is this spec related?

New Tag would be nice

Hi,

Since the last Tag (1.6.1) is from 23 Oct 2015, it would be really nice if you guys could Tag a new version, so that the various fixes and improvements would be available to the wider audience.

Make the client PSR-7 compatible

Building off of #20 and thephpleague/oauth2-client#224, I think it would be good for oauth1-client to move to a HTTP client that is PSR-7 compatible. It will allow arbitrary request/response handling and make the client easier to extend for specific provider implementations.

Ivory is usable now, and Guzzle 6 (next release) will be PSR-7 compatible.

This will be a breaking change and probably require a major version bump.

Class 'Symfony\Component\EventDispatcher\Event' not found

Hey,

Event class not found when I'm using oauth1-client with my laravel project.

  • laravel version: 7.*
  • Symfony event dispatcher: 5.*

I was trying to install 4.* version of event dispatcher. But it created conflict with laravel project.

So do oauth1-client only works with event dispatcher 5?

Twitter Callback URL Question

According to their most recent announcement, June 12th will deprecate open Callbacks, where a whitelist must be specified. In their documentation, it specifies the callback param must be callback_url however, the PHP Client specifies callback_uri as per the example on the README.

Updating this to say callback_url results in an error and incorrect callback from Twitter. As a test, even updating it to callback_uro results in the same behavior as callback_url. Why is it that callback_uri works when the documentation explicitly says to use callback_url?

$server = new League\OAuth1\Client\Server\Twitter(array(
    'identifier' => 'your-identifier',
    'secret' => 'your-secret',
    'callback_uri' => "http://your-callback-uri/",
));

Breaking change for v1.8.0

Hi all! I'm not sure what's considered the public API of this package, but the most recent update has broken the socialiteproviders/providers package which allows social logins in Laravel. It'll also have broken any custom OAuth providers which extend the League\OAuth1\Client\Server\Server class, due to the typehinting of the methods.

In this particular case, it's made more problematic by the fact that Laravel socialite defines its own user to return, so the typehintinh for getUserDetails cannot be met without changes in several repositories.

Was this release meant as a minor release, or should it be upgraded to a major to stop any existing extensions being broken?

[PHP 8] Warning on EncodesUrl

The following PHP warning is generated under PHP 8:

League/OAuth1/Client/Signature/HmacSha1Signature::League/OAuth1/Client/Signature/{closure}(): 
Argument #2 ($value) must be passed by reference, value given in 
/vendor/league/oauth1-client/src/Signature/EncodesUrl.php on line 54

Seems to be caused by the second parameter being passed as a reference. Removing the '&' symbol from value seems to work for me, but I don't know if there are greater implications outside of my particular use case.

Tumblr does not accept oauth_signature when trying to get access token

Signature of the request passes fine when I'm getting the OAuth token, but it fails when I try to get the access token. The error that I get from Tumblr is this:

oauth_signature does not match expected value

I tried to Google the error, but the only reasons I found were typos. I verified that I didn't make a mistake, but the error is still there. I appreciate your help!

Connect oauth1-client to a Magento OAuth1 server

I created a script to add the option to connect to my own Magento OAuth1 server. And I am having a problem. It's not working.

I have put die(); function everywhere to try to catch the problem and I still get a empty white page.

But from using die(); function everywhere I now know that the method : __construct and createClientCredentials of the PHP script Server.php work and execute. I also know that the variable $clientCredentials in __construct has values in its array.

So up to that point everything seems to be working but it stops somewhere. Is there a way to track the problem lies?

Here is information on Magento OAuth1 server:

http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html

Here is my code :

namespace League\OAuth1\Client\Server;

use League\OAuth1\Client\Credentials\TokenCredentials;

class Magento extends Server
{
    /**
     * {@inheritdoc}
     */
    public function urlTemporaryCredentials()
    {
        die('urlTemporaryCredentials');
        return 'https://url.com/store/oauth/initiate';
    }

    /**
     * {@inheritdoc}
     */
    public function urlAuthorization()
    {
        die('urlAuthorization');
        return 'https://url.com/store/oauth/authorize';
    }

    /**
     * {@inheritdoc}
     */
    public function urlTokenCredentials()
    {
        die('urlTokenCredentials');
        return 'https://url.com/store/oauth/token';
    }

    /**
     * {@inheritdoc}
     */
    public function urlUserDetails()
    {
        die('urlUserDetails');
        // return 'https://api.twitter.com/1.1/account/verify_credentials.json';
    }

    /**
     * {@inheritdoc}
     */
    public function userDetails($data, TokenCredentials $tokenCredentials)
    {
        die('userDetails');
    [...]

Also, I am using the allback_uri for the testing. This is where I get the blank page.

[2.0] Move providers to separate projects

@bencorlett Now that the develop branch is fresh with some of the new architecture I wanted to bring up the topic of moving the provider implementations to independent repositories. I noticed that there are some empty repos within thephpleague organization. Were those created with this purpose in mind?

I am happy to assume responsibility for a few of them to get the ball rolling. I'd prefer to take trello, tumblr, twitter, and bitbucket, as I have experience with those APIs.

What are your thoughts?

Query strings with arrays cannot be properly signed

I've encountered an issue whereby if you create a service that extends League\OAuth1\Client\Server\Server and use $this->getHeaders(...) with a query string that has array notation (i.e. var[]=whatever) then the URL cannot be properly signed.

Here's an example:

$this->getHeaders($this->tokenCredentials, 'GET', 'https://myservice.com/hello?a=1&b=2&c[]=3&c[]=4&d[a]=5&d[b]=6');

This generates a warning: Warning: rawurlencode() expects parameter 1 to be string, array given in /my/proj/vendor/league/oauth1-client/src/Client/Signature/HmacSha1Signature.php on line 66

Which means that the service is sending an invalid signature.

When I dug deeper, it looks like the method League\OAuth1\Client\Signature\HmacSha1Signature::baseString does not properly operate on such nested arrays. Specifically this line: $data[rawurlencode($key)] = rawurlencode($value);. The method rawurlencode doesn't know how to act on an array.

Is this a bug or did I miss another way to sign a URL here?

Client version: 1.6.1

php -a
Interactive shell

php > parse_str('a=1&b=2&c[]=3&c[]=4&d[a]=5&d[b]=6', $query);
php > var_dump($query);
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  string(1) "2"
  ["c"]=>
  array(2) {
    [0]=>
    string(1) "3"
    [1]=>
    string(1) "4"
  }
  ["d"]=>
  array(2) {
    ["a"]=>
    string(1) "5"
    ["b"]=>
    string(1) "6"
  }
}
php > foreach ($query as $key => $val) { var_dump(rawurlencode($key), rawurlencode($val)); }
string(1) "a"
string(1) "1"
string(1) "b"
string(1) "2"

Warning: rawurlencode() expects parameter 1 to be string, array given in php shell code on line 1
string(1) "c"
NULL

Warning: rawurlencode() expects parameter 1 to be string, array given in php shell code on line 1
string(1) "d"
NULL
php > 

Create generic Server for access to basic signing processes

I have another project that currently includes the following method:

private function buildSignedUrl($unsigned_url)
{
        $token = $this->buildToken();
        $consumer = $this->buildConsumer();
        $signature_method = $this->getSignature();
        $oauthrequest = OAuthRequest::from_consumer_and_token(
            $consumer,
            $token,
            'GET',
            $unsigned_url
        );
        $oauthrequest->sign_request($signature_method, $consumer, $token);
        return $oauthrequest->to_url();
}

The OAuthRequest class and the implementations within the buildToken & buildConsumer & getSignature methods come from a basic OAuth toolkit.

The toolkit is outdated, poorly designed, and not tested; it is effective. I would prefer to use a modern package like thephpleague/oauth1-client to complete the task described above.

The use case for this implementation is tied to a OAuth service that does not permit an Authentication flow to obtain the TokenCredentials, instead they are issued to you via the account console. So, you need to provide all four pieces of information and sign the request before completing the transaction with the service. Very annoying.

Do you think it is worthwhile to explore a solution in the project? I am happy to put in the effort; I want to gauge the response before beginning.

What about using guzzlehttp/oauth-subscriber ?

Hi,

I'm starting to contribute to your project, writing a JIRA provider; so I was looking at the code when I noticed a few things.
You are using Guzzle as the HTTP client but you don't use its Oauth1 subscriber implementation, is there a particular reason for that ?
I think it would be interesting to use it since it take care of all the headers and signatures stuff, and it will dramatically reduce your codebase.

I would have written a PR if that was not such a big change. Of course I could if you're interested.

Good job by the way, your library is way more easy to implement than Atlassian own JIRA examples I tried.

Custom Server Class

I need to have a custom Server class because I need to overwrite the getTokenCredentials permanently for everything that would extend my Server.

Now the issue is that I need to extend the existing League\OAuth1\Client\Server\Server which has tons of abstract methods that need to be implemented which results in the following Server class for me.

<?php

use League\OAuth1\Client\Credentials\TemporaryCredentials;
use League\OAuth1\Client\Credentials\TokenCredentials;

class Server extends \League\OAuth1\Client\Server\Server
{
    public function getTokenCredentials(TemporaryCredentials $temporaryCredentials, $temporaryIdentifier, $verifier)
    {
        // my new getTokenCredentials-method
    }

    public function urlTemporaryCredentials()
    {
        //
    }

    public function urlAuthorization()
    {
        //
    }

    public function urlTokenCredentials()
    {
        //
    }

    public function urlUserDetails()
    {
        //
    }

    public function userDetails($data, TokenCredentials $tokenCredentials)
    {
        //
    }

    public function userUid($data, TokenCredentials $tokenCredentials)
    {
        //
    }

    public function userEmail($data, TokenCredentials $tokenCredentials)
    {
        //
    }

    public function userScreenName($data, TokenCredentials $tokenCredentials)
    {
        //
    }
}

So what would be your advice on how to build my custom Server class without having this bunch of empty methods?

Guzzle HTTP Client configuration

I really want to pass the configuration to Guzzle HTTP Client for setting timeout, and I have a proposal for that.

Add $clientOptions to the constructor of /src/Client/Server/Server.php

abstract class Server
{
    /**
     * @var array
     */
    protected $clientOptions;

    /**
     * Create a new server instance.
     *
     * @param ClientCredentialsInterface|array $clientCredentials
     * @param SignatureInterface               $signature
     * @param array  $clientOptions
     */
    public function __construct($clientCredentials, SignatureInterface $signature = null, $clientOptions)

Composer deprecation notices

When installing, I get the following deprecation notices from Composer. Please update these files so that the file name matches the class name.

Deprecation Notice: Class League\OAuth1\Client\Tests\TrelloTest located in ./vendor/league/oauth1-client/tests/TrelloServerTest.php does not comply with psr-4 autoloading standard.
Deprecation Notice: Class League\OAuth1\Client\Tests\XingTest located in ./vendor/league/oauth1-client/tests/XingServerTest.php does not comply with psr-4 autoloading standard.
Deprecation Notice: Class League\OAuth1\Client\Tests\ServerStub located in ./vendor/league/oauth1-client/tests/stubs/ServerStub.php does not comply with psr-4 autoloading standard.

Problem with league/oauth1-client version 1.6.2 upgrading to 1.7

it seems that there is something wrong with upgrading guzzlehttp and the socialite required package league/oauth1-client.
I just tried to upgrade my laravel to laravel 7.0 and also my socialite to 4.4 and guzzlehttp/guzzle package to 7.0 the latest but the package of league/oath1-client downgrades from 1.7 to 1.6.2 which uses guzzle/guzzle instead of guzzlehttp/guzzle. so I am facing the deprecated warning
Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.

actually I have deleted composer.lock and vendor folder and then composer update but no help.
and also I had problem and error 500 while I wanted to login through google

Options for authorization URL

In the same vein as the OAuth2 client the OAuth1 client should allow for additional options when constructing the Authorization Url. As per OAuth 1 RFC 5849:

Servers MAY specify additional parameters.

A second parameter for $options that would merge with the token from temp credentials would be ideal IMHO.

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.