I'm using the PEAR OAuth Class to access the LinkedIn developer API and I've come across a bit of a problem. I can authorize my application but when it comes to getting an accessToken I'm receiving this error:
Edit:
Code after Adam's suggestions
public function oauth_access()
{
session_start();
$token = $_GET['oauth_token'];
$verifier = $_GET['oauth_verifier'];
$secret = $_SESSION['trequest_token_secret'];
$key = "****";
$secret = "****";
$oauthc = new OAuth($key, $secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauthc->setToken($token, $secret);
$oauthc->setNonce(rand());
try
{
$access_token_info = $oauthc->getAccessToken("https://api.linkedin.com/uas/oauth/accessToken");
$_SESSION['laccess_oauth_token']= $access_token_info['oauth_token'];
$_SESSION['laccess_oauth_token_secret']= $access_token_info['oauth_token_secret'];
$_SESSION['loauth_verifier'] = $verifier;
}
catch (OAuthException $e)
{
echo $e->getMessage();
}
}
But I'm now getting a different error:
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
You don't need to manually compute the signature, as pecl/oauth will do that for you.
Also, you're telling the library to pass the data in the Authorization HTTP header. That is a good place to have it. Then you are passing it via a query parameter. That is permitted, but less optimal. (You may actually be passing it in two places.) Also, pecl/oauth will automatically generate the proper timestamp.
When I first started, I found this blog post to be a good first start.
Or you can use the LinkedIn PHP library listed by Paul. It's also a good place to begin, if you don't want to reuse pecl/oauth because you're using that someplace else.
Related
I'm trying the following thing for quite a while now and am heavily struggling...
On a website, I first want to authenticate a user with his Google Account using OAuth. Therefore, I'm using this library. In order to get it working, I used $f3->set('AUTOLOAD','vendor/ikkez/f3-opauth/lib/opauth/'); to load the PHP files and then used the following code to create the routes and make the authentication possible:
$f3 = \Base::instance();
// load opauth config (allow token resolve)
$f3->config('vendor/ikkez/f3-opauth/lib/opauth/opauth.ini', TRUE);
// init with config
$opauth = OpauthBridge::instance($f3->opauth);
// define login handler
$opauth->onSuccess(function($data){
header('Content-Type: text');
//$data['credentials']['token'];
});
// define error handler
$opauth->onAbort(function($data){
header('Content-Type: text');
echo 'Auth request was canceled.'."\n";
print_r($data);
});
So far so good, thats all working fine, once permission is granted from Google I get the correct callback, also including the login token.
Now the next step is, that after user gave permission for that (by authenticating), I want to check, if the user subscribed to a specific channel on Youtube (and afterwards saving that information to my DB, printing it at the first step would be enough though).
Now I did my homework for multiple hours in trying to figuring out how it works...
What I (in general found) is that the following curl request should give me the desired result:
curl \
'https://youtube.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&forChannelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&mine=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
I then tried to sent this curl request with PHP, substituting the API KEY with my Google API Key and "YOUR_ACCESS_TOKEN" with the token I got from OAUTH.... However, it's throwing an error, saying "request had insufficient authentication scopes"... That seems to be because when checking the PHP example from Google, I have to provide the Scopes I'm using - in my case https://www.googleapis.com/auth/youtube.readonly.
The PHP code provided by Google is the following:
<?php
/**
* Sample PHP code for youtube.subscriptions.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'forChannelId' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'mine' => true
];
$response = $service->subscriptions->listSubscriptions('snippet,contentDetails', $queryParams);
print_r($response);
This let's me run into a new issue... Trying to use this code, I'm getting the error, that Google_Client is not known as class... I then went ahead and installed Google Client with Composer and tried to use vendor/autoload.php in order to use the class.... However, when including the autoload.php, I get the error Fatal error: Cannot declare class Prefab, because the name is already in use... This seems to be the case, because the f3-opauth declares this Prefab class already and then the google apiclient tries to declare it again... However, I didn't manage to to include google apiclient without the autoload...
You see, I really tried a lot and I've been working on this for about 5-6 hours today, only getting that one API request to work and I don't know what else to try...
Any hint on how to get it working would be appreciated - if there's any hint on doing it a completely other way, I'd be willing to change it as well, as the project itself just started.
Summarizing, what I'm trying to do is the following:
-> User can log in on Website with his Youtube/Google Account
-> When authenticating, its checked, if the User is a Subscriber of a specific channel. Next step would be to also check, if he is a channel member of this speicific channel. Both information would need to be saved to database
-> after that, user can always log in into his account with Google again and in the database, you can find the information if the user is subscriber and/or channel member of this channel..
Thanks in advance!
I'm not sure if this will help with your exact use case, but I've worked with Google APIs in the past with Fat-Free. I couldn't get it to work right off the bat, so I installed and got it working with the Google Client/API/SDK. Once I got that working, then I worked backwards to see if I could make it work with Fat-Free. One of the things that I noticed I was running into was missing fields in the Oauth request. access_type was one that got me as well as approval_prompt. I know that you said you've gotten your access token thus far, so it may not apply, but it could for future requests. Here's some example code I've got working to generate an oauth URL for Google Sign in, and then to process the request and make the call to the userinfo portion.
<?php
class App_Auth {
public static function generateOauthUrl() {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('scope', 'profile email');
$Oauth->set('response_type', 'code');
$Oauth->set('access_type', 'online');
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->uri('https://accounts.google.com/o/oauth2/auth', true);
}
public static function processAuthCodeAndGetToken($auth_code) {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('client_secret', $fw->get('google.client_secret'));
$Oauth->set('scope', 'profile email');
$Oauth->set('access_type', 'online');
$Oauth->set('grant_type', 'authorization_code');
$Oauth->set('code', $auth_code);
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->request('https://oauth2.googleapis.com/token', 'POST');
}
public static function getOauthUserInfo($access_token) {
$Oauth_User_Info = new \Web\OAuth2();
return $Oauth_User_Info->request('https://www.googleapis.com/oauth2/v2/userinfo', 'GET', $access_token);
}
One other error that has bitten me in the backside was we would get our access token from Google and then store it in the database for subsequent requests. We would get that scopes error you mentioned request had insufficient authentication scopes. We eventually figured out that the access_token was longer than our database field (VARCHAR(32) if I remember right) so we needed to make our database field longer so it would store the whole thing.
Hopefully one of those triggers something for you to figure out your issue.
I want to get valid link https://bitbucket.org/{username}/rss/feed?token={token} (this is main problem) and then get valid response from this link in CLI.
I know my required parameters, e.g. consumer_key, consumer_secret, request_token_url, authenticate_url, access_token_url.
I tried to use StudioIbizz\OAuth\OAuth1, but is seems to be designed for Browser, not for CLI.
I tried to run:
$this->OAuth = new \StudioIbizz\OAuth\OAuth1($this->consumer_key,$this->consumer_secret);
$requestToken = $this->OAuth->getRequestToken($this->request_token_url,$this->authenticate_url);
$token = $requestToken['oauth_token_secret'];
and paste this $token to my RSS link, but then I see message You must have read access to access the RSS feed. from Bitbucket.
I need Step by Step instructions for serious dummies.
Edit: I tried this:
$accessToken = $this->OAuth->getAccessToken($this->access_token_url,$requestToken['oauth_token_secret'],$requestToken['oauth_token']);
But then I get this:
Fatal error: Uncaught exception 'StudioIbizz\OAuth\OAuthException' with message 'Unexpected HTTP status #400'
I don't see any function related with that on official documentation. Maybe that feature not exists.
For more information, you could use this link:
https://confluence.atlassian.com/bitbucket/use-the-bitbucket-cloud-rest-apis-222724129.html
You could use stevenmaguire's Bitbucket OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
$provider = new Stevenmaguire\OAuth2\Client\Provider\Bitbucket([
'clientId' => '{bitbucket-client-id}',
'clientSecret' => '{bitbucket-client-secret}',
'redirectUri' => 'https://example.com/callback-url'
]);
$token = $_GET['code'];
To get an RSS token for Bitbucket via PHP CLI, you will need to use the OAuth 1.0a protocol to authenticate your request. Here are the steps you can follow:
Install an OAuth library for PHP that can be used in CLI, such as the league/oauth1-client package.
Create a new instance of the OAuth client by passing in your consumer key and consumer secret.
$client = new League\OAuth1\Client\Server\Bitbucket($consumerKey, $consumerSecret);
Get the request token by calling the getTemporaryCredentials method and passing in the callback URL.
$temporaryCredentials = $client->getTemporaryCredentials();
Get the authorization URL by calling the getAuthorizationUrl method and passing in the temporary credentials.
$authorizationUrl = $client->getAuthorizationUrl($temporaryCredentials);
Use this URL to authenticate the request via the browser.
After successful authentication, you will get a verifier code.
Get the access token by calling the getTokenCredentials method and passing in the temporary credentials and the verifier code.
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
$tokenCredentials = $client->getTokenCredentials($temporaryCredentials, $verifier);
Get the RSS token by calling the getRssToken method and passing in the token credentials
$rssToken = $client->getRssToken($tokenCredentials);
You can use this token to construct your RSS feed link:
https://bitbucket.org/{username}/rss/feed?token={$rssToken}
Note that, this is just a general idea of how to use the OAuth library and it may vary depending on the library you are using. It's also important to check the documentation of that library for more details.
I have a browser-based app (single page, AngularJS) and am using hello to use third party signin such as Google, FB, Soundcloud, etc.
My app uses a PHP API server.
What's a good way to have the user able to login using Google, but also verify the user on the server side?
I was considering:
The browser app performs an implicit grant with google/fb/etc
I then transfer the access_token from the client to the server, then use, for example, a google-api-php-client with my app id, secret and the user access_token? Using their API such as /me? (which grant type would this be?)
Retrieve some key from the third-party (facebook_id, email, etc), match it against a user in my database, and then consider the user authenticated?
Also, should I perform this on each API request? Or should I just stash the access_token for a bit and assume that the user is still valid until the key expires?
One issue is that not all of those providers support the implicit flow. But assuming they do, the access_token you get for each will be proof that the user authenticated with that system, not necessarily that they have access to call your API. You still need something that asserts that "someone#gmail.com can 'read' resource X in your system"
You probably need something that translates whatever you get from Google, Soundcloud, etc. into a token your app understands. A simple(r) format is to use JWT. (Json Web Tokens).
App -> Intermmediary -> Soundcloud/Google
<-JWT--+ <---whavetever-+
and then:
App - (JWT) -> API
JWT are easy to manipulate, validate and verify. See jwt.io
You might want to look at this blog post also for some additional information (specifically on AngularJS front-ends)
The blog post #eugenio-pace mentioned was really helpful for setting up the client side.
For the server side though, the access_token should be validated.
The SDK's are (in composer) (code below):
Facebook: "facebook/php-sdk-v4" : "4.0.*"
Google: cURL request (didn't care for "google/apiclient")
SoundCloud: "ise/php-soundcloud": "3.*"
(There are others of course, just these three were the ones I chose, and seem decent.)
Last time I did something like this I made the mistake of validating the access_token on every request, which had a huge (obviously negative) impact on performance. Now I just validate it on login and use it to retrieve the user's ID from that service. So, the browser sends me access_token A and says it's from Facebook, I use the sdk above the the access_token with Facebook, and I get back their ID so I know they are who they say they are.
I'd suggest storing the access_token on the server with the expires_in.
(I haven't dealt with refresh token's yet)
Code to validate tokens using the above libraries:
function validateTokenFacebook($token, $id=null) {
// Performed above
// FacebookSession::setDefaultApplication($config->fb->app_id, $config->fb->secret);
$session = new FacebookSession($token);
// Fetch user info
$request = new FacebookRequest($session, 'GET', '/me');
try {
$response = $request->execute();
} catch (\Facebook\FacebookServerException $e) {
$this->mlog->err($e . "\n" . $e->getTraceAsString());
throw new AuthTokenInvalidException();
}
$graphObject = $response->getGraphObject();
$user_id = $graphObject->getProperty('id');
return array(access_token, $user_id);
}
function validateTokenGoogle($token, $id=null) {
$resp=array();
// This key isn't included in the token from hello.js, but
// google needs it
if (!array_key_exists('created', $token)) $token['created'] = $token['expires'] - $token['expires_in'];
$client = new \Google_Client();
$client->setClientId($this->systemConfig->google->app_id);
$client->setClientSecret($this->systemConfig->google->secret);
$client->setRedirectUri($this->systemConfig->google->redirectUri);
$client->setScopes('email');
$client->setAccessToken(json_encode($token));
try {
// Send Client Request
$objOAuthService = new \Google_Service_Oauth2($client);
$userData = $objOAuthService->userinfo->get();
return array($token['access_token'], $userData['id']);
} catch (\Google_Auth_Exception $e) {
throw new AuthException('Google returned ' . get_class($e));
}
}
function validateTokenSoundcloud($token, $id=null) {
$soundcloud = new \Soundcloud\Service(
$this->systemConfig->soundcloud->app_id,
$this->systemConfig->soundcloud->secret,
$this->systemConfig->soundcloud->redirect);
$soundcloud->setAccessToken($access_token);
try {
$response = json_decode($soundcloud->get('me'), true);
if (array_key_exists('id', $response))
return array($access_token, $response['id']);
} catch (Soundcloud\Exception\InvalidHttpResponseCodeException $e) {
$this->mlog->err($e->getMessage());
}
throw new AuthTokenInvalidException();
}
I have a few custom classes above, such as the Exceptions and the systemConfig, but I think it's verbose enough to communicate what they do.
I'm currently attempting to install a login button for LinkedIn onto my website. I'm trying to go step by step as the developers section shows. After I wrote the code to get a request token and checked it using print_r.
define("my consumer key");
define("my consumer secret");
$oauth = new OAuth(my consumer key, my consumer secret);
//The first item of business is getting a request token
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
if($request_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was:"
. $oauth->getLastResponse());
} else {
$request_token = $request_token_response;
}
print "Request Token:\n";
printf(" - oauth_token = %s\n", $request_token['oauth_token']);
printf(" - oauth_token_secret = %s\n", $request_token['oauth_token_secret']);
print "\n";
I got "Fatal error:Uncaught exception 'OAuthException'...Peer certificate cannot be authenticated with known CA certificates". The line that was called for the error is below
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
I am not understanding what that error is trying to tell me so that I can fix the problem. I would appreciate and tips or guidance to help me better understand what this error message is trying to convey and how to fix it.
It seems that the library is trying to verify the SSL certificate and it cannot do so. You could disable ssl checks via the method OAuth::disableSSLChecks. I assume you are using the following pecl extension http://www.php.net/manual/en/class.oauth.php. If not the client library you are using should have a method to disable the SSL certificate verification.
....
...
$oauth = new OAuth(my consumer key, my consumer secret);
$oauth->disableSSLChecks();
..
...
Ideally you would do it right after instantiation
In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9