I'm using y0lk package to help me with OAuth1 and ETSY App, I managed to get the temporary credentials, but can't get my hand on Access tokens.
here's what I do :
$client = new Etsy([
'identifier' => '*********************',
'secret' => '*********',
'scope' => 'listings_r transactions_r',
'callback_uri' => 'http://*********.loc/slider/'
]);
$tempCred = $client->getTemporaryCredentials();
$tmpSecret = $tempCred->getSecret();
$tmpId = $tempCred->getIdentifier();
// Redirect to Etsy Autorisation login page
$redirect_url = $client->getAuthorizationUrl($tempCred);
$accessTokens = $client->getTokenCredentials($tempCred, $tmpId, $_GET['oauth_verifier']);
Ok, I don't know how to do, because to obtain the oauth verifier ( and do the $_GET['oauth_verifier']), I have to go by the login page, and then, to get the access token, I need my temp credentials, but to get then I 'll have to go again by new Etsy and this is why I always got the token revoked error..
I'm beginner, in PHP and with API, if someone see other mistakes in my way to do this, feel free to point them out for me :)
Thank you for your time.
Related
I am having trouble accessing calendar events of users using the Microsoft Graph api and get a access denied response even though I have set all of the correct permissions and more, both application and delegated for (Calendars.Read Delegated, Calendars.Read Application, Calendars.Read.Shared Delegated, Calendars.ReadBasic Delegated, Calendars.ReadBasic.All Application, Calendars.ReadWrite Delegated, Calendars.ReadWrite Application, Calendars.ReadWrite.Shared Delegated). I am using the microsoft developer instant sandbox users who all have Microsoft 365 E5 Developer licences and all have Exchange Online Plan 2.
The code I use to retrieve the access token and send the calendar request is below:
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => 'https://graph.microsoft.com/.default',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
$graph = new Graph();
$graph->setBaseUrl("https://graph.microsoft.com/")
->setAccessToken($accessToken);
$ptr = $graph->createCollectionRequest('GET', '/users/{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}/events')
->setPageSize(100);
If I use the same code with the endpoint /users/{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}/calendars I get a list of the users calendars but as soon as I try to get events I get a 403 error. The same issue occours if I use the deligated auth flow and try to access events as a signed in user, again I am able to access a list of calendars.
When decoding the access token the roles section looks like this:
"roles": [
"Calendars.Read",
"Mail.ReadBasic.All",
"Group.Read.All",
"User.Read.All",
"Calendars.ReadBasic.All",
"GroupMember.Read.All",
"Calendars.ReadWrite",
"Mail.Send"
]
Are there other permissions that need to be set for an app or a user to make this work?
Let me know if I can add any more info to help with answers, sny sugesstions would be helpful
Thanks
UPDATE
Having looked further it could be an issue with "Limiting application permissions to specific Exchange Online mailboxes" (https://learn.microsoft.com/en-us/graph/auth-limit-mailbox-access)
There was a policy defined but having removed this (and waiting for that update to become effective) I am still getting the same error. I assume therefore that a policy is needed to allow access however I can't find any documentation about this.
So the fix (given here https://learn.microsoft.com/en-us/answers/questions/1167148/microsoft-graph-throwing-403-error-for-calendar-wi) is to only have the lowest level permission, otherwise you get the error response.
Sorry but I am just learning about Microsoft Graph and I have spent the last 4 hours scouring Google to find my answer and my brain is going to explode so I have resorted to Stack.
I was using a previous method to authenticate a user to Azure AD but it has no more support and I want to switch over to Microsoft Graph. I am able to get the access token but that is as far as I get.
At this point all I want to do send the user to the Microsoft Login page so they can authenticate and be redirected back to my web app. I have read so much I don't know what else I can read. Is there anyone who can point me in the right direction to how to get this accomplished? also where in the world is the documentation for this?
$guzzle = new \GuzzleHttp\Client();
$tenantId = "***********************************";
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => '***********************************',
'client_secret' => '***********************************',
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
'redirect_uri' => 'https://www.example.com/here'
],
])->getBody()->getContents());
$accessToken = $token->access_token;
// Create a new Graph client.
$graph = new Graph();
$graph->setAccessToken($accessToken);
Comment moved to answer:
As I said in the comments, if you need to log in as a user and authenticate, please don't use a daemon-based client credential flow because there is no user interaction with this flow. You should use the authentication code flow, which requires you to log in to the user and obtain the authorization code, and then use the authorization code to redeem the access token.
Sample for your referenceļ¼
OAuth 2.0 PHP Sample Code.
Authentication and Authorization Using Auth0 in PHP.
Microsoft Graph Connect Sample for PHP.
I am using the tymondesigns/jwt-auth package for my app. I use customClaims to make my token.
Here is the code for login :
$token_data = [
'iss' => new Issuer('AreteHCM'),
'iat' => new IssuedAt(Carbon::now()) ,
'exp' => new Expiration(Carbon::now()->addDays(1)),
'nbf' => new NotBefore(Carbon::now()),
'sub' => new Subject('AreteHCMS'),
'jti' => new JwtId('AreteHCM'),
'user_data' => $user->user,
'menu_access' => $menu_access,
'login_time' => Carbon::now(),
];
$customClaims = JWTFactory::customClaims($token_data);
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload)->get();
For Logout, I invalidate the token, so the token can not be used anymore after the user logout.
JWTAuth::invalidate(JWTAuth::getToken());
I'm creating API (Backend) and the front end team using Angular. Eveythings went smooth, until the user logout and try to login again. After login, the user get the new account, but when he/she wants to access my middleware always rejects the token, it says that the token is blacklisted.
Here is my middleware :
$token = JWTAuth::getToken();
$data = JWTAuth::getPayload($token)->toArray();
It always shows error :
The token has been blacklisted in file C:\xampp\htdocs\aretehcm\vendor\tymon\jwt-auth\src\Manager.php on line 109
What I want to approach is :
User login get new token to access the API (every API request requires header auth Bearer token)
User logout will invalidate the token, so the token can not be used anymore to access the API
User login will get a new token so he/she can access the API
Is there any misconception from me about the JWT-API architecture ?
Thank you in advance for your replies and answers.
A quick google search pointed me towards this solution:
https://github.com/tymondesigns/jwt-auth/issues/983#issuecomment-275884324
I am the owner and admin of a LinkedIn company page: https://www.linkedin.com/company/{id}/.
I want to connect to LinkedIn and get return a JSON-feed with latest 10 posts on my company wall to display on my website so I touch on the service https://api.linkedin.com/v1/companies/{id}/updates?format=json.
The JSON is outputted in linkedin.php. This file is then included in my web page, say index.php.
I have registrered an app at https://developer.linkedin.com. I have entered my Client ID and Client Secret in PHP-LinkedIn-SDK available here https://github.com/ashwinks/PHP-LinkedIn-SDK.
I followed the developer documentation I need to authenticate first. When I run linkedin.php I am redirected to sign into my LinkedIn profile. I have to finish this step in order to touch the service above.
With the current solution my users will have to login into LinkedIn when they access my website.
How can I access a list of my company's LinkedIn posts without prompting my users to sign in?
Thanks.
1. Generate your access token
Follow the documentation https://github.com/ashwinks/PHP-LinkedIn-SDK to create a login link.
2. Save your access token
Once you get it, it will be available for 60 days. Save it into your database.
3. Fetch your company posts
You can use the same access token to fetch company contents
$li = new LinkedIn(...);
$li->setAccessToken(YOUR_ACCESS_TOKEN);
$posts = $li->get('/companies/YOUR_COMPANY_ID/updates/');
4. Manage response
Cache or display the response after parsing it.
Hope that helps,
Use https://packagist.org/packages/linkedinapi/linkedin
$li = new LinkedIn(
array(
'api_key' => 'yourapikey',
'api_secret' => 'yourapisecret',
'callback_url' => 'https://yourdomain.com/redirecthere'
)
);
//Get the login URL - this accepts an array of SCOPES
$url = $li->getLoginUrl(
array(
LinkedIn::SCOPE_BASIC_PROFILE,
LinkedIn::SCOPE_EMAIL_ADDRESS,
LinkedIn::SCOPE_NETWORK
)
);
/*LinkedIn will redirect to 'callback_url' with an access token as the 'code' parameter. You might want to store the token in your session so the user doesn't have to log in again*/
$token = $li->getAccessToken($_REQUEST['code']);
$token_expires = $li->getAccessTokenExpiration();
//Make a request to the API
$info = $li->get('/people/~:(first-name,last-name,positions)');
$li = new LinkedIn(
array(
'api_key' => 'yourapikey',
'api_secret' => 'yourapisecret',
'callback_url' => 'https://yourdomain.com/redirecthere',
'curl_options' => array(
CURLOPT_PROXY => '127.0.0.1:80',
),
)
)
I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use