How to make a request with PHPLeague oAuth2 client? - php

I'm integrating with a affiliate platform for a client which provides an oAuth2 API, don't usually do massive amounts of work with oAuth2.
I've decided for my client, I'll use the PHP Leagues oAuth2 package: https://github.com/thephpleague/oauth2-client
Anyway, I've got an accessToken no problem! using the following:
$provider = new GenericProvider([
'clientId' => $this->config->affiliates->rakuten->clientId,
'clientSecret' => $this->config->affiliates->rakuten->clientSecret,
'redirectUri' => 'http://www.newintoday.com/',
'urlAuthorize' => 'https://api.rakutenmarketing.com/token', // Ignore
'urlAccessToken' => 'https://api.rakutenmarketing.com/token',
'urlResourceOwnerDetails' => 'https://api.rakutenmarketing.com/' // Ignore
]);
try {
// Try to get an access token using the resource owner password credentials grant.
$accessToken = $provider->getAccessToken('password', [
'username' => $this->config->affiliates->rakuten->username,
'password' => $this->config->affiliates->rakuten->password,
'scope' => $this->config->affiliates->rakuten->publisherId,
]);
$productSearchApiBaseUri = 'https://api.rakutenmarketing.com/productsearch/1.0';
$request = $provider->getAuthenticatedRequest('GET', $productSearchApiBaseUri, $accessToken, [
'body' => '?keyword=shirt',
]);
\Utils::dump($provider->getResponse($request));
} catch (IdentityProviderException $e) {
echo $e->getMessage();
}
My question is once we have the accessToken what do we use in it to make the request, I followed through the code and came up with the above but the API responds saying that the keyword is not specified? Is
$request = $provider->getAuthenticatedRequest('GET', $productSearchApiBaseUri, $accessToken, [
'body' => 'keyword=shirt',
]);
The correct way to provide it with a GET variable?
Thanks in advance.

Realised I could simply include the get vars in the URI alla:
$productSearchApiBaseUri = 'https://api.rakutenmarketing.com/productsearch/1.0?keyword=shirt';

Related

Why does Microsoft Graph API deny my request to upload files to OneDrive from a PHP website?

I have a website where my clients can view their invoices and upload design assets related to the invoice. I want to create a PHP form which uploads the files to OneDrive, instead of storing them on our web server.
I have followed the instructions in this StackOverflow answer to get started.
I have created the app in Microsoft Azure, and entered the appropriate Application (client) ID, Object ID, and Directory (tenant) ID. I am using a client secret to authorize the application, and submitting a POST request using my account's email and password to get the access token.
The relevant code for my upload form looks like this:
if (isset($_FILES['uploads'])) {
$guzzle = new \GuzzleHttp\Client();
$tenantId = 'xxxxxx';
$clientId = 'xxxxxx';
$clientSecret = 'xxxxxx';
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
$user_token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'password',
'username' => 'xxxxxx#companydomain.com',
'password' => 'xxxxxx'
],
])->getBody()->getContents());
$user_accessToken = $user_token->access_token;
$graph = new Graph();
$graph->setAccessToken($user_accessToken);
foreach ($_FILES['uploads']['name'] as $key => $name) {
try {
$graph->createRequest(
"PUT", "/drive/root:/Documents/".$_FILES['uploads']['name'][$key].":/content"
)->upload(
$_FILES['uploads']['tmp_name'][$key]
);
} catch (Exception $e) {
var_dump($e);
}
}
}
This code throws an exception, showing the following error message when I try to upload a :
Client error: `PUT https://graph.microsoft.com/v1.0/drive/root:/Documents/Screen%20Shot%202022-10-30%20at%204.03.44%20PM.png:/content` resulted in a `403 Forbidden` response
In the Azure API Permissions, I have granted the Files.Read.All, Files.ReadWrite.All, and User.Read permissions. However, when I check the access token in https://jwt.ms/, I just see "scp": "User.Read".
So it looks like my access token might not have the correct permissions, but I can see that I do have permissions to read and write files when I look at the API Permissions page in Azure.
How can I further debug this issue and find a solution to upload files from my server to OneDrive?
Thanks to Nikolay's comment, I added a scope parameter to form_params and that fixed it.
I also changed the grant_type to client_credentials, and removed the username/password authorization.
$user_token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
'scope' => 'https://graph.microsoft.com/.default'
],
])->getBody()->getContents());
$user_accessToken = $user_token->access_token;

How to setup O365 made possible login with thephpleague/oauth2-client and working with msgraph-sdk-php?

I try to implement a php client, access a mailbox of a user with graph api. Because it's a background service, which should fetching specific mails attachment, it must run with grant type password.
So far, I got it really easy working make a login with thephpleague/oauth2-client and grant type client_credentials:
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '...',
'clientSecret' => '...',
'redirectUri' => 'https://login.microsoftonline.com/common/oauth2/nativeclient',
'urlAuthorize' => null,
'urlAccessToken' => 'https://login.microsoftonline.com/.../oauth2/token?api-version=1.0',
'urlResourceOwnerDetails' => 'https://graph.microsoft.com/v1.0/me',
]);
$accessToken = $provider->getAccessToken('client_credentials');
Now I try it with grant type password, but it fails:
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => '...',
'clientSecret' => '...',
'redirectUri' => 'https://login.microsoftonline.com/common/oauth2/nativeclient',
'urlAuthorize' => null,
'urlAccessToken' => 'https://login.microsoftonline.com/.../oauth2/token?api-version=1.0',
'urlResourceOwnerDetails' => 'https://graph.microsoft.com/v1.0/me',
]);
$accessToken = $provider->getAccessToken('password', [
'username' => '...',
'password' => '...',
]);
Response I get: invalid_request. Google that error, I come to https://learn.microsoft.com/de-de/azure/active-directory/develop/v2-oauth2-auth-code-flow which tells me, I should fix my request.
Now... somehow it's hard, finding a) a ressource telling which urls are right and b) finding a tutorial, tell how I add right a app so I can get it working (maybe also a result, because the o365 layout changes fast...)
Does anyone have a idea, what the right parameters are and what I must do in the Azure Active Directory Admin Center so its working?
My goal is "only", access a users mailbox and get attachments from existing mails. I think, when I can authenticate successfully, all other things are easy (hope so).
Please refer to the official tutorial: Authenticate with the Microsoft Graph service.
To authenticate as an application you can use the Guzzle HTTP client, which comes preinstalled with this library, for example like this:
<?php
require __DIR__ . '/vendor/autoload.php';
$guzzle = new \GuzzleHttp\Client();
$tenantId = 'your_tenanet_id, e4c9ab4e-****-****-****-230ba2a757fb';
$clientId = 'your_app_id_registered_in_portal, dc175b96-****-****-****-ea03e56da5e7';
$clientSecret = 'app_key_generated_in_portal, /pGggH************************Zr732';
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
$user_token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'password',
'username' => 'your_user_id, jack#***.onmcirosoft.com',
'password' => 'your_password'
],
])->getBody()->getContents());
$user_accessToken = $user_token->access_token;
$graph = new Graph();
$graph->setAccessToken($user_accessToken );
$response = $graph->createRequest('Get','/me/messages')
->setReturnType(Model\Message::class)
->execute();
?>
Note that the resource should be https://graph.microsoft.com/

How can I send cookie while using REST API?

Using Laravel 5 and trying to send some data from my site to another one, which provides me with the REST API. But they use cookies as a authorization. For this moment, I've passed auth successfully. And stuck on how should I send this cookie to API interface via POST method? Here is my listing.
Thanx in advance.
P.S. All things are going on inside the controller.
if (Cookie::get('amoauth') !== null) {
//COOKIE IS HERE
$client = new Client();
$newlead = $client->post('https://domain.amocrm.ru/private/api/v2/json/leads/set', [
'add' => [
'add/name' => 'TEST LEAD',
'add/date_create' => time(),
'add/last_modified' => time(),
'add/status_id' => '1',
'add/price' => 5000
]
]);
} else {
$client = new Client();
$auth = $client->post('https://domain.amocrm.ru/private/api/auth.php',[
'USER_LOGIN' => 'login',
'USER_HASH' => 'hash',
'type' => 'json'
]);
$auth = $auth->getHeaders('Set-Cookie');
Cookie::queue('amoauth', $auth, 15);
return redirect('/test');
}
Now it returns me the following:
Client error: `POST https://domain.amocrm.ru/private/api/v2/json/leads/set` resulted in a `401 Unauthorized` response.
Found the solution: switched to ixudra/curl.

Laravel Passport Password Grant Refresh Token

Trying to wrap my head around using Laravel's Passport with mobile clients. The Password Grant type of authentication seems to be the way to go, and i have it working with my iOS app, however i can't get token refreshing to work.
When authenticating i get a token and a refresh token which i store, however when the token expires, calling the oauth/token/refresh route doesn't work. The route is using the web middleware which means my app using the api route can't access it. I'm not sure if they intended for mobile clients to never refresh or if they wanted you to roll your own refreshing? If anyone has insight on how this is supposed to work, that'd be great.
The oauth/token/refresh route is not for refreshing access tokens. It is used to refresh transient tokens, which are used when you consume your own API from your javascript.
To use your refresh_token to refresh your access token, you need to call the oauth/token route with the grant_type of refresh_token.
This is the example provided by the documentation:
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'the-refresh-token',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
One note about scopes, when you refresh the token, you can only obtain identical or narrower scopes than the original access token. If you attempt to get a scope that was not provided by the original access token, you will get an error.
I've done something like.
Created an endpoint for grant refresh token.
and in my controller,
public function userRefreshToken(Request $request)
{
$client = DB::table('oauth_clients')
->where('password_client', true)
->first();
$data = [
'grant_type' => 'refresh_token',
'refresh_token' => $request->refresh_token,
'client_id' => $client->id,
'client_secret' => $client->secret,
'scope' => ''
];
$request = Request::create('/oauth/token', 'POST', $data);
$content = json_decode(app()->handle($request)->getContent());
return response()->json([
'error' => false,
'data' => [
'meta' => [
'token' => $content->access_token,
'refresh_token' => $content->refresh_token,
'type' => 'Bearer'
]
]
], Response::HTTP_OK);
}

How to use LinkedIn People Search API

As there are several changes in LinkedIn People Search API as of now,please explain how to use this API for people search by company and etc...
I have read
https://developer-programs.linkedin.com/documents/people-search-api
and other document but not getting connection with search link and API key and all.As explained in document we can search some thing like this
https://api.linkedin.com/v1/people-search?keywords=Princess
but where we need to put API KEY and all. I am new to APIs so please if possible explain this.
I have also go through other blogs but they are old and not applicable.
If possible please also mention possibility and things we cann't do.
LinkedIn's People Search API has not been available to the open developer community since May, 2015.
You can apply to be a developer partner at: https://developer.linkedin.com/partner-programs/apply
If you are an official partner of LinkedIn and still have access to that API, you should follow up with your assigned Partner Engineering representative for further assistance, rather than public forums.
Use Postman to follow this tutorial:
https://developer.linkedin.com/docs/oauth2
On succes you can click to get the PHP code you need to create the request with OATH2. I have no developer account on LinkedIn so that part you have to do yourself.
The example GET request would look like this in PHP:
Step 2
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://www.linkedin.com/uas/oauth2/authorization');
$request->setRequestMethod('GET');
$request->setQuery(new http\QueryString(array(
'response_type' => 'code',
'client_id' => '123456789',
'redirect_uri' => 'https://www.example.com/auth/linkedin',
'state' => '987654321',
'scope' => 'r_basicprofile'
)));
$request->setHeaders(array(
'cache-control' => 'no-cache'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
Step 3
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://www.linkedin.com/uas/oauth2/accessToken');
$request->setRequestMethod('POST');
$request->setQuery(new http\QueryString(array(
'grant_type' => 'authorization_code',
'code' => '987654321',
'redirect_uri' => 'https://www.myapp.com/auth/linkedin',
'client_id' => '123456789',
'client_secret' => 'shhdonottell'
)));
$request->setHeaders(array(
'postman-token' => 'bee6f5d7-a0e6-4a76-6ef8-930c95af53a6',
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded',
'host' => 'www.linkedin.com'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();

Categories