Using this oauth2 library for PHP, I am validating a user via client_credentials like this:
server.php
$server = new OAuth2\Server($storage, [
'access_lifetime' => 3600, // 1 hour
'refresh_token_lifetime' => 50400, // 14 days
]);
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($server->getStorage('client_credentials'), ['always_issue_new_refresh_token' => true])));
Then in my endpoint (token.php):
require_once __DIR__.'/server.php';
$request = OAuth2\Request::createFromGlobals();
$server->handleTokenRequest($request)->send(); //returns the token object
Although a new access_token is returned, no refresh_token is returned:
{"access_token":"501a3d087db7532d4e4350402f9a5da332d71dfc","expires_in":3600,"token_type":"Bearer","scope":null}
How do you get the refresh_token?
This is a normal behaviour.
With the Client Credentials grant type the refresh tokens are useless because the client can get a new access token by asking a new one when he wants.
Moreover I found a closed issue where the author of the library you use clearly explains that there is no bug here.
As mentioned in this answer, you will find in the RFC6749 section 4.4.3 that the refresh token SHOULD NOT be included.
You can also read this question and the accepted answer.
You must specify accessType: 'offline' in the OAuth2 options to receive a refresh token. If the former does not work try access_type: 'offline'.
Related
With help from #CarlZhao I am finally getting a good understanding of the difference between OAuth and Graph. I am building the capability in my app for users to post messages to a team channel. So far I can list teams, channels, and delete channels. I am having a hard time trying to send a chatMessage. I understand that because sending a chatMessage is a delegated permission and not an application permission so from my understanding I have to use the accessToken created from OAuth when the user authenticated with my app.
What I am doing is saving that token in my database so I can call it when I am trying to send a chatMessage. Not sure if that is correct. So in my code, I am creating a new Graph instance, but I am using the access token of the user and not the token of the graph.
$useraccesstoken = "************************************";
// create a new OAuth graph from useraccesstoken
$graph_message = new Graph();
$graph_message->setAccessToken($useraccesstoken);
// post message
$data = [
'body' => [
'content' => 'This is a message from the API I made it works'
],
];
$message = $graph_message->createRequest("POST", "/teams/$group_id/channels/$channel_id/messages")
->addHeaders(array("Content-Type" => "application/json"))
->attachBody($data)
->setReturnType(Model\User::class)
->execute();
This is producing no errors, but nothing happens and the chatMessage is not posted. I have double-checked and my $group_id and $channel_id are correct.
Am I using the $useraccesstoken correctly? can I start a new Graph() instance with the $useraccesstoken?
Yes, you could start a new Graph() instance with the $useraccesstoken.
The graph API of sending messages doesn't return User::class. Try your code with
->setReturnType(Model\ChatMessage::class)
The access token is invalid for one hour by default, see here. You could not use it all the time, so it seems you don't need to store in the database. It's better to refresh token before the access token expires, and this step shows you how to refresh token.
The default is 1 hour - after 1 hour, the client must use the refresh
token to (usually silently) acquire a new refresh token and access
token.
I am using php oauth2 library from this github repo.
PHP oauth2 library
Whenever i send a refresh token, I receive new access token with old scopes.
But i want to change the scopes returned with new access token.
When i first generate a token using user credentials grant type, I get the supported scopes for the user and store them this way.
$defaultScope = implode(" ", $scopes);$memory = new OAuth2\Storage\Memory(array('default_scope' =>$defaultScope));
$scopeUtil = new OAuth2\Scope($memory);
$this->server->setScopeUtil($scopeUtil);
$this->server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
where $scopes is an array
for example $scopes=array("ADDUSER","EDITUSER","EDITROLE");
similarly , if i send refresh token using refresh_token grant type and run this with modified $scopes
for example $scopes=array("ADDUSER", "EDITROLE");
$defaultScope = implode(" ", $scopes);$memory = new OAuth2\Storage\Memory(array('default_scope' =>$defaultScope));
$scopeUtil = new OAuth2\Scope($memory);
$this->server->setScopeUtil($scopeUtil);
$this->server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
I receive same old scopes("ADDUSER EDITUSER EDITROLE") which were set when new access token generated using user credentials grant type.
SO is there a way to change scopes when new access token is generated using refresh token ?
or am i doing something wrong here?
A Client can "down-scope" when it asks for a new access token in the refresh token grant, see the documentation around scope in the spec here: https://www.rfc-editor.org/rfc/rfc6749#section-6 Yet your Authorization server may or may not support that.
I'm using PHPoAuthLib in order to connect to the QuickBooks API per their example
When I follow their example, the first request that I make to the API works perfectly:
$result = json_decode($quickbooksService->request($url));
echo 'result: <pre>' . print_r($result, true) . '</pre>';
However in their example they use $_GET['oauth_token'] and $_GET['oauth_verifier'] to request an access token, and these values are only available on the $_GET server variable during the single callback from QuickBooks Online immediately after my app has been authorized.
For future requests there are no such examples on PHPoAuthLib's docs, so I tried a quick homebrew solution:
Save the response from QBO somewhere
if (!empty($_GET['oauth_token']) {
file_put_contents("token.txt", json_encode([
'oauth_token' => $_GET['oauth_token'],
'oauth_verifier' => $_GET['oauth_verifier'],
'realm_id' => $_GET['realmId']
]));
}
Use that response again later
$token = json_decode(file_get_contents("token.txt"));
$quickbooksService->requestAccessToken(
$token->oauth_token,
$token->oauth_verifier
// $token->getRequestTokenSecret() is not necessary - it will be automatically populated
);
// At this point my app crashes and return a 500 error
// Further code does not run
The error I receive is:
TokenResponseException in StreamClient.php line 68:
Failed to request resource. HTTP Code: HTTP/1.1 401 Unauthorized
Remember that the token and verifier work perfectly if I use them immediately after the app is authorized. If I save them to a file and attempt to re-use them 30 seconds later, this happens.
I think it might be a fundamental misconception about OAuth 1.0
I don't think what you have is a correct OAuth implementation. Have you read the OAuth spec and implemented as it's defined there?
Once you have a request token and a verifier, you use those to get an access token.
That access token is then good for 6 months.
It looks like you're trying to use a short-lived request token to continually fetch access tokens instead. That won't work.
i.e. If you're doing this everytime you want to make another request:
$quickbooksService->requestAccessToken(
Then you're doing something wrong. You should be doing that ONCE every 6 months, and that's it.
Working code here:
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/IntuitAnywhere.php
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/OAuth.php
https://github.com/consolibyte/quickbooks-php
Spec is here:
http://oauth.net/core/1.0a/#auth_step3
I got a problem with oAuth authentification in magento.
I used following guide to create connection:
http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html
First of all I granted all privileges for all accounts in magento / System / WebServices / REST ... Also I created oAuth Consumer. I got with it two variables (key and secret).
According the guide (Getting an Unauthorized Request Token) I configured RESTClient for Firefox. Selected oAuth 1.0 option, inserted data from magento and added them to headers.
And now I have something like that:
http://www.mg19.local/oauth/initiate
OAuth oauth_version="1.0",
oauth_signature_method="PLAINTEXT",
oauth_nonce="pzmp8IZuroEP6gf",
oauth_timestamp="1410271763",
oauth_consumer_key="9ad2067e70a4c3b799ab2799203b3e3b",
oauth_signature="a37633084e79432568181ef00410140e%26"
Then if I submit this, I will get following error:
Status Code: 400 Bad Request
oauth_problem=parameter_absent&oauth_parameters_absent=oauth_callback
I don't know the main purpose of the callback link, therefore I used random link. For example: http://www.mg19.local
When i submit
http://www.mg19.local/oauth/initiate/?oauth_callback=http://www.mg19.local
I got following result:
oauth_token=e00fc8386ba523bdd1d79a2fe61d59cb&oauth_token_secret=ca0d999010b2b149e2d51feefc328722&oauth_callback_confirmed=true
According the guide I moved to the 2nd step (User Authorization):
I copied data from the response to request. And forward the link:
http://www.mg19.local/oauth/authorize
I redirected to the following page:
Authorize application
Postman requests access to your account
After authorization application will have access to you account.
Authorize | Reject
And when I select Authorize I'm getting the following error:
An error occurred. Your authorization request is invalid.
Using xDebug I have found that the problem is near:
/**
* Load token object, validate it depending on request type, set access data and save
*
* #return Mage_Oauth_Model_Server
* #throws Mage_Oauth_Exception
*/
protected function _initToken()
{
....
} elseif (self::REQUEST_AUTHORIZE == $this->_requestType) {
if ($this->_token->getAuthorized()) {
$this->_throwException('', self::ERR_TOKEN_USED);
...
I'm not sure, but I think, once autorization finished successfully, then I moved from index to account area page and when authorization start again - it fail and I move on index again.
Please give any advice.
For what I see, the callback URL is the one that is messing up the whole thing. Callback is the most important link in OAuth. The callback should be a valid URL pointing to you site.
Once the user logs in auth server (Magneto in your case) Magneto will do a callback to the Callback URI you provided with the oauth_verifier. Like below:
/callback?oauth_token=tz2kmxyf3lagl3o95xnox9ia15k6mpt3&oauth_verifier=cbwwh03alr5huiz5c76wi4l21zf05eb0
Then your server should all the token API /oauth/token with the all the required Authorization headers below. Pasted from Magneto document link you provided
oauth_consumer_key - the Consumer Key value provided after the registration of the application.
oauth_nonce - a random value, uniquely generated by the application.
oauth_signature_method - name of the signature method used to sign the request. Can have one of the following values: HMAC-SHA1, RSA-SHA1, and PLAINTEXT.
oauth_signature - a generated value (signature).
oauth_timestamp - a positive integer, expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
oauth_token - the oauth_token value (Request Token) received from the previous steps.
oauth_verifier - the verification code that is tied to the Request Token.
oauth_version - OAuth version.
Hope this makes it clear. Please read the sections User Authorization and Getting Access Token sections of the link you pasted.
I'm using Guzzle and had a real hard time with it. In my case it was failing because I was using oauth_callback instead of callback, it worked when I changed it to:
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
$stack = HandlerStack::create();
$middleware = new Oauth1([
'consumer_key' => $key,
'consumer_secret' => $secret,
'token' => null,
'token_secret' => null,
'callback' => 'https://callback.co.uk'
]);
$stack->push($middleware);
$client = new Client([
'base_uri' => $magentoCredentials->shopUrl,
'handler' => $stack
]);
$res = $client->post('/oauth/initiate?oauth_callback', ['auth' => 'oauth']);
it's weird this morning all my facebook applications don't work anymore. And when I use the graph API using request like : "graph.facebook.com/me"
I got :
{
"error": {
"type": "OAuthException",
"message": "An active access token must be used to query information about the current user."
}
}
Any idea?
Facebook did a developer update the past couple days..
http://developers.facebook.com/blog/post/518/
We had problems with the API key on older versions of the sdk, check that.
same thing here. I followed Ben Biddington's blog to get the access token. Same error when trying to use it. Facebook's OAuth implementation doesn't follow the spec completely, i am fine with it as long as the doc is clear, which obviously is not the case here. Aslo, it would be nice if the userid and username are returned with the access token.
You need to create an app so that you can get an appId and secret. Then you can create a facebook object like so:
$fb = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => $cookie
));
and get the access token with $fb->getAccessToken(); this can then be appended to your graph api call url, and it should work.
when you click on facebook button, after login one cookie is generated with fbs_(token_access). by which it understands that you are logged in. may be because you are going directly you dont have sufficient access to get json encoded data..
this can be the problem for you.. make sure when you are loggedd in,cookie is generated ..
As the message states, you need to provide a valid access token. If you aren't providing one, then it obviously is the problem, as you need to have one, even when accessing your own information. If you are providing one, and it gives that error, then the token is not valid, which may be because it has expired or been revoked.