I try to use jumbojett library for php and openid. I made connection but and get secret id and client, but when I want to get token I don't know how.
In small documentation is next example:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
// this assumes success (to validate check if the access_token property is there and a valid JWT) :
$clientCredentialsToken = $oidc->requestClientCredentialsToken()->access_token;
But function requestClientCredentialsToken() doesn't exist in library. Does anyone know how to get token or to recommend some another php library where I can define scope, redirect uri, get client secret and id from open server and offcourse to get token.
Thanks in advance
There is a public function getAccessToken().
You should modify the the code above like this:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
$oicd->authenticate();
$mytoken=$oidc->getAccessToken();
Related
I have a problem about the error code 105 (Message: "Authentication failed. Either supplied credentials are invalid or the account is inactive") when performing a "GetUser" request. I've already understand that it's because of an incorrect access token (AuthenticationToken header element) or developer token for the target environment. So it must be about the way I set my credentials (or my credentials). Here is my code:
public function getAuthorization()
{
$result = AuthController::getRefreshToken(); //get The refresh token, update it if necessary
AuthController::WriteOAuthRefreshToken($result); //stock the refresh token
$authentication = (new OAuthWebAuthCodeGrant())
->withEnvironment(AuthController::ApiEnvironment) //production
->withClientSecret(AuthController::ClientSecret)
->withClientId(AuthController::ClientId)
->withOAuthTokens(
(new OAuthTokens())
->withAccessToken(json_decode($result, true)["access_token"])
->withRefreshToken(json_decode($result, true)["refresh_token"])
->withAccessTokenExpiresInSeconds(3600))
->withRedirectUri(AuthController::RedirectUri)
->withState(rand(0,999999999));
$GLOBALS['AuthorizationData'] = (new AuthorizationData())
->withAuthentication($authentication)
->withDeveloperToken(AuthController::DeveloperToken);
AuthController::Authenticate();
}
And here is the function to Authenticate which call the getUser Function ()
static function Authenticate()
{
// Authenticate for Bing Ads services with a Microsoft Account. Perform a $GLOBALS['AuthorizationData']->Authentication->RequestOAuthTokensByRefreshToken($refreshToken);
AuthController::AuthenticateWithOAuth();
$GLOBALS['CustomerManagementProxy'] = new ServiceClient(
ServiceClientType::CustomerManagementVersion12,
$GLOBALS['AuthorizationData'],
AuthController::ApiEnvironment);
$GLOBALS['CustomerManagementProxy']->SetAuthorizationData($GLOBALS['AuthorizationData']);
// Here is the problem
$user = AuthController::GetUser(null, true)->User;
}
The getUser function I currently use is the same as the one in the PHP "Code Syntax" part in the documentation.
I'm using the production environment with my own credentials. I've already checked my developer token and all the corresponding rights (which seems correct). I update my tokens each time I'm trying to do that request.
Is there any problems about the way I set the request?
If the problem is about the tokens, is there a way to check if it's correct?
I precise I've tried also with the getAccount function with the same result.
Any ideas? Thanks for your time.
Here are a few ideas to explore:
Can you login to the Bing Ads web application with these credentials i.e., does this user have access to a Bing Ads account?
Is the OAuthTokens->AccessToken set or empty e.g., try var_dump($authentication).
Try refreshing the token directly in the auth object e.g., see this sample.
Log the SOAP request and response to see if AuthenticationToken was set in the GetUser call e.g., immediately after the GetUser call print the last request/response:
print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\n";
print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\n";
Otherwise to confirm credentials you might want to contact Bing Ads support directly.
I hope this helps!
I am currently new to using php and Laravel and working with an API however I have been following the Spotify PHP tutorial https://github.com/jwilsson/spotify-web-api-php.
I've also put in bold some of my questions that I wanted to ask , hopefully someone can help.
I have followed all steps but need help just to get it working.
Put the following code in its own file, lets call it auth.php. Replace CLIENT_ID and CLIENT_SECRET with the values given to you by Spotify.
(Where abouts should I save this file?)
The REDIRECT_URI is the one you entered when creating the Spotify app, make sure it's an exact match.
(I used my localhost:8888/callback/ not sure if that is correct?) Obviously I haven't put me details in here on this website as for security reasons.
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ ID',
'CLIENT_SECRET',
'REDIRECT_URL'
);
$options = [
'scope' => [
'playlist-read-private',
'user-read-private',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
?>
When the user has approved your app, Spotify will redirect the user together with a code to the specifed redirect URI. You'll need to use this code to request a access token from Spotify.
put this code in a new file called callback.php:
Do replace client id and secret with my detail? also how do I save the access token?
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
// Request a access token using the code from Spotify
$session->requestAccessToken($_GET['code']);
$accessToken = $session->getAccessToken();
$refreshToken = $session->getRefreshToken();
// Store the access and refresh tokens somewhere. In a database for example.
// Send the user along and fetch some data!
header('Location: app.php');
die();
In a third file, app.php, tell the API wrapper which access token to use, and then make some API calls!
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
require 'vendor/autoload.php';
$api = new SpotifyWebAPI\SpotifyWebAPI();
// Fetch the saved access token from somewhere. A database for example.
$api->setAccessToken($accessToken);
// It's now possible to request data about the currently authenticated user
print_r(
$api->me()
);
// Getting Spotify catalog data is of course also possible
print_r(
$api->getTrack('7EjyzZcbLxW7PaaLua9Ksb')
);
(Where abouts should I save this file?)
You can save this file in differents places in laravel, for testing you could write it in a controller (not the best but you can).
Do replace client id and secret with my detail?
Yes of course !
also how do I save the access token?
You can save in a database or in a session or where you want. If you store it in a session you will have to make a new request to get a new Access token if the user logged out of your application. In a database you can reuse it.
Many access token are only available for a specific duration. The spotify doc should speak of it.
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
For testing you can do this in your controller, but it's a good idea to have a service layer where you put the business logic of your application.
Do not copy require 'vendor/autoload.php'; in your file laravel handle the composer autoload already.
This is my first time posting here, so forgive me if I leave out something important. Anyway, I'm trying to connect to Etsy's API using PHP and OAuth. I've been following the guide here: https://www.etsy.com/developers/documentation/getting_started/oauth#section_obtaining_temporary_credentials
I already created an account and app on Etsy, so I have my consumer key and secret. I've copied their code for getting a request token 100% and defined the two variables using my unique key and secret. However, when I try to make the http request, I get an "ERR_EMPTY_RESPONSE". When I click to get more detail it says: "Unable to load the webpage because the server sent no data". Here is a screenshot of the error page: http://imgur.com/dgxAlci
I'm using MAMP to make a localhost on port 8888 in order to test any PHP code that I write (e.g. to get to this php file I enter this url: localhost:8888/Etsy/EtsyOAuth.php).
My code is below. I edited out my key and secret.
define('OAUTH_CONSUMER_KEY', "****");
define('OAUTH_CONSUMER_SECRET', "****");
// instantiate the OAuth object
// OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET are constants holding your key and secret
// and are always used when instantiating the OAuth object
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
// make an API request for your temporary credentials
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r", 'oob');
print $req_token['login_url']."\n";
I'm using pHP 5.6.7 and OAuth 1.2.3 says phpinfo().
Any help is much appreciated. Thanks in advance!
I simply don't really understand how this whole OAuth authentification thing works and I'm pretty much stuck. I'm trying to let a user authentificate his/her YouTube account to my server using the Google PHP Client API.
Here's my current code:
<?php
require_once app_path().'/google-apis/Google_Client.php';
require_once app_path().'/google-apis/contrib/Google_YouTubeService.php';
class SignupController extends BaseController {
public function showSignupForm() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$youtube = new Google_YoutubeService($client);
$client->authenticate(Input::get('code'));
$token = json_decode($client->getAccessToken());
return View::make('signup')->with('google_token', $token->access_token);
}
public function getYTAccess() {
$client = new Google_Client();
$client->setClientId('CLIENTID');
$client->setClientSecret('CLIENTSECRET');
$client->setAccessType('offline');
$client->setDeveloperKey('DEVKEY');
$client->setRedirectUri('REDIRECT_URI');
$youtube = new Google_YoutubeService($client);
$authUrl = $client->createAuthUrl();
return View::make('connect_youtube')->with('authUrl', $authUrl);;
}
}
?>
This is the code for the SignupController in the Laravel-based application I'm building. The relevant routes are as follows:
Route::get('signup/connect_youtube/return', 'SignupController#showSignupForm');
Route::get('signup', 'SignupController#getYTAccess');
I only get an invalid request error after getting redirected to my application and I know it has something to do with the access token, just don't know what.
Any help would be appreciated.
Thanks
Tobias Timpe
(Secrets omitted, obviously)
To put it simply, there are 2 steps (at least) you have to do:
1. pass the correct parameters to google. The parameters tell you 1. who you are (you need to present your client id and client secret), 2. what you ask for (in your case youtube scope) 3. redirect_uri which is where your user will be redirected back after she accepts your app's request. 4. other options like access_type=offline which specifies that you have a backend server to continue the auth flow.
To check that this step works correctly, you don't always need run the code. Just print out your auth_url that the sdk makes for you. All those parameters i mentioned should be embedded there. Copy-paste the url in the browser, if the parameters are correct, it will take you to Google's consent page. If not, most likely is because the parameters you set in Google Apis setting page are mismatched with your parameters scripted in the auth_url. Examples are mismatched domains, redirect_uris, client_ids, client_secrets. I'm not sure if this is the error that you are receiving.
If your parameters are good, Google will let your user to login and allow youtube scope access for your app ('consent'). It will redirect user's browser back to your specified 'redirect_uri' with the parameter code=. So this will get you to the step 2 your server script has to process.
The value shooted from Google in the parameter ?code is what you need to get access token. So your server route (redirect_uri) needs to extract the code parameter and pass to the google api to exchange for 'credentials'. Note that the auth code can be used only once. The response credentials will contain access_token and refresh_token. These are important for the api calling so you need to persist them in a storage, possibly with google sdk you are using.
Hope that helps.
I've successfully made my way through the LinkedIn OAuth process (using the REST API - OAuth 1.0a). However I'm having trouble with my first API call after the callback. I set the UserToken, UserTokenSecret and UserVerfier in the library I am writing, and this call this function to get my profile information:
public function getUserProfile()
{
$consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
$auth_token = new OAuthConsumer($this->getUserToken(), $this->getUserTokenSecret());
$access_token_req = new OAuthRequest("GET", $this->access_token_endpoint);
$params['oauth_verifier'] = $this->getUserVerifier();
$access_token_req = $access_token_req->from_consumer_and_token($this->consumer,
$auth_token, "GET", $this->access_token_endpoint, $params);
$access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,
$auth_token);
$after_access_request = $this->doHttpRequest($access_token_req->to_url());
$access_tokens = array();
parse_str($after_access_request,$access_tokens);
# line 234 below
$access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
var_dump($after_request);
}
The function var_dumps a string, which is the basic synopsis of my profile:
string(402) " User Name etc. etc. http://www.linkedin.com/profile?viewProfile=&key=28141694&authToken=HWBC&authType=name&trk=api*a137731*s146100* "
That's good. However, the minute I refresh the page, the same function call fails with:
Undefined index: oauth_token, line number: 234
(this line marked with comment in above code block).
Then, of course, the var_dump reports this error from LinkedIn:
string(290) " 401 1310652477038 R8MHA2787T 0 [unauthorized]. The token used in the OAuth request is not valid. "
something to note:
the user token, secret, and verifier are persisted during the initial authorization callback (right before this function is called). So, they are the same during the first call (when it works, right after coming back from linkedin) and during a page reload (when it fails on line 234).
Also, I must admit I'm not 100% sure I understand everything that's going on in this function. I actually took examples from this tutorial (about a different service, not linkedin) http://apiwiki.justin.tv/mediawiki/index.php/OAuth_PHP_Tutorial and combined it with the information I gathered from the LinkedIn API documentation, spread throughout their developer site. Most notable was the addition of the 'verifier' which the tutorial did not use.
Any insight into this problem would be greatly appreciated. Thanks in advance.
-Nick
UPDATE
The only way I've been able to get this going is to do a new OAuth handshake every single time. Is this the way it's supposed to happen? I was under the impression that once I got my user token/secret and verifier, that I could then use these for continuous API calls until the token expired or was revoked.
As it is now, every time the page reloads I'm requesting a new user token, secret and verifier, then immediately calling to get the user profile (which succeeds). Next reload, I get a whole new key/secret and verifier. Seems like quite a lot of work for each call, and as I understood it, you should be able to perform offline operations with this method - and if I need new authorization each time, then I guess I can't do that?
Well. I've finally figured out what was going on so thought I'd post the answer here, just in case someone else runs into this.
The example that I was using as a guide was flawed. After the access token is retrieved, you should then create a new OAuthRequest object, instead of using the existing $access_token_req instance.
So this:
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
Should be changed to this:
$api_req = new OAuthRequest("GET", $this->api_url.$api_call);
// prepare for get profile call
$api_req = $api_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$api_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($api_req->to_url());