@@ -44,8 +44,80 @@ http client with oauth credentials before making a request.
4444 $response = $user->get();
4545 ```
4646
47+ ### OAuth2 authorization
48+
49+ You can use ` OAuth2Listener ` in order to make authorized requests using version 2 of OAuth protocol.
50+
51+ #### OAuth2 client credentials (_ 2-legged flow_ )
52+
53+ ``` php
54+ // @see: https://bitbucket.org/account/user/<username or team >/api
55+ $oauth_params = array(
56+ 'client_id' => 'aaa',
57+ 'client_secret' => 'bbb'
58+ );
59+
60+ $bitbucket = new \Bitbucket\API\Api();
61+ $bitbucket->getClient()->addListener(
62+ new \Bitbucket\API\Http\Listener\OAuth2Listener($oauth_params)
63+ );
64+
65+ $repositories = $bitbucket->api('Repositories');
66+ $response = $repositories->all('my_account'); // should include private repositories
67+ ```
68+
69+ #### OAuth2 Authorization code (_ 3-legged flow_ )
70+
71+ You can use any 3rd party library to complete this [ flow] [ 3 ] and set ` access_token ` option when you instantiate ` OAuth2Listener ` .
72+
73+ In the following example [ PHP League's OAuth 2.0 Client] [ 1 ] is used with [ Bitbucket Provider] [ 2 ] .
74+
75+ ``` php
76+ session_start();
77+
78+ $provider = new Stevenmaguire\OAuth2\Client\Provider\Bitbucket([
79+ 'clientId' => $_ENV['bitbucket_consumer_key'],
80+ 'clientSecret' => $_ENV['bitbucket_consumer_secret'],
81+ 'redirectUri' => 'http://example.com/bitbucket_login.php'
82+ ]);
83+ if (!isset($_GET['code'])) {
84+
85+ // If we don't have an authorization code then get one
86+ $authUrl = $provider->getAuthorizationUrl();
87+ $_SESSION['oauth2state'] = $provider->getState();
88+ header('Location: '.$authUrl);
89+ exit;
90+
91+ // Check given state against previously stored one to mitigate CSRF attack
92+ } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
93+
94+ unset($_SESSION['oauth2state']);
95+ exit('Invalid state');
96+
97+ } else {
98+
99+ // Try to get an access token (using the authorization code grant)
100+ $token = $provider->getAccessToken('authorization_code', [
101+ 'code' => $_GET['code']
102+ ]);
103+
104+ $bitbucket = new Bitbucket\API\Repositories();
105+ $bitbucket->getClient()->addListener(
106+ new \Bitbucket\API\Http\Listener\OAuth2Listener(
107+ array('access_token' => $token->getToken())
108+ )
109+ );
110+
111+ echo $bitbucket->all('my_account')->getContent(); // should include private repositories
112+ }
113+ ```
114+
47115----
48116
49117#### Related:
50118 * [ Authentication @ BB Wiki] ( https://confluence.atlassian.com/display/BITBUCKET/Use+the+Bitbucket+REST+APIs#UsetheBitbucketRESTAPIs-Authentication )
51119 * [ OAuth on Bitbucket @ BB Wiki] ( https://confluence.atlassian.com/display/BITBUCKET/OAuth+on+Bitbucket )
120+
121+ [ 1 ] : http://oauth2-client.thephpleague.com/
122+ [ 2 ] : https://github.com/stevenmaguire/oauth2-bitbucket
123+ [ 3 ] : http://oauthbible.com/#oauth-2-three-legged
0 commit comments