Symfony HttpClient, fail to authenticate external API witch Bearer - rest

I have a problem, I try to use a external API, but the response of that APi is a 401.
1º- I send a request to get the auth token, works fine.
$auth = $this->client->request(
'POST',
'https://api.namebright.com/auth/token',
[
'body' => [
'grant_type' => 'client_credentials',
'client_id' => $clientID,
'client_secret' => $clientSecret,
],
]
);
2º- handler token, i dump the token is loocks fine
$token = sprintf('Bearer %s', $auth->toArray()['access_token']);
3º- I make other request to get the API response, i got a 401.
$response = $this->client->request(
'GET',
'http://api.namebright.com/rest/purchase/availability/google.pt',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => $token,
],
]
);
I don't know what i'm doing wrong. :(
I checked, for responses on the internet and i don't see the problem.
I Tried to change Authorization to authorization.
I tried to check the token in the postmen, works fine.

Related

guzzle3 add token Post Request

I am working on a project using an old version of Guzzle (version 3), I'd like to add a token to the post request, can't find how to do it, I have looked on the doc there is no example for that , here is what I tried so far :
<?php
$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => ['Bearer', $token]
));
$req = $client->post($url);
$client->send($req)->getBody(true);
?>
$client->setDefaultOption('auth', array(null, 'Bearer'.$token ))
I keep getting :
Guzzle\Http\Exception\ClientErrorResponseException: Client error response [status code] 400 [reason phrase] Bad Request [url]
I found the solution :
`$client = new Client();
$client->setDefaultOption('headers', array(
'Authorization' => 'Bearer '.$token,
));`
So instead of array in Authorization I sent a string that contains the token

Convert cURL to Guzzle POST with --form-params and --header

I'm struggling with a given curl-request which I want to handle over guzzle.
The curl-request looks like this:
curl --location --request POST "https://apis.myrest.com" \
--header "Content-Type: multipart/form-data" \
--header "Authorization: Bearer YOUR-BEARER-TOKEN" \
--form "mediaUrl=https://myfile.mpg" \
--form "configuration={
\"speechModel\": { \"language\": \"en-US\" },
\"publish\": {
\"callbacks\": [{
\"url\" : \"https://example.org/callback\"
}]
}
}
And I want it to send via guzzle like that:
// 1. build guzzle client:
//----------------------------------------------------------------------
$this->client = new Client([
'base_uri' => $this->config->getBaseUri(),
]);
// 2. build guzzle request:
//----------------------------------------------------------------------
$request = new Request(
'POST',
'myendpoint',
[
'authorization' => 'Bearer ' . $this->config->getApiToken(),
'cache-control' => 'no-cache',
'content-type' => 'application/json',
// maybe here, or not?
form_params => ['mediaUrl' => 'www.media.com'],
]
);
// 3. send via client
//----------------------------------------------------------------------
response = $this->client->send($request, ['timeout' => self::TIMEOUT]);
My problem now is, that I have no clue how to handle this. In guzzle's documentation i found "form_params":
http://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request#post-form-requests
But it does not seem to work. If I add the form_params-array to my request, the receiver does not get them. Can anybody tell me, how to write the exact curl-command with guzzle?
Thanks
Try using multipart instead of form_params.
http://docs.guzzlephp.org/en/latest/request-options.html#form-params
From Guzzle documentation:
form_params cannot be used with the multipart option. You will need to
use one or the other. Use form_params for
application/x-www-form-urlencoded requests, and multipart for
multipart/form-data requests.
Additionally try setting Guzzle Client with debug on, as it will display raw HTTP request that it sends, so you can compare it more easily with the curl command.
http://docs.guzzlephp.org/en/latest/request-options.html#debug
It is difficult to understand what is the exact request you would like to send, because there is incosistencies between the curl example and your code. I tried to replicate the curl as best as I could. Please note that Request 3rd parameter only expects headers, and for request options you have to use the 2nd parameter of send.
$client = new Client([
'base_uri' => 'https://example.org',
'http_errors' => false
]);
$request = new Request(
'POST',
'/test',
[
'Authorization' => 'Bearer 19237192837129387',
'Content-Type' => 'multipart/form-data',
]
);
$response = $client->send($request, [
'timeout' => 10,
'debug' => true,
'multipart' => [
[
'name' => 'mediaUrl',
'contents' => 'https://myfile.mpg'
],
[
'name' => 'configuration',
'contents' => json_encode([
'speechModel' => [
'language' => 'en-US'
],
'publish' => [
'callbacks' =>
[
[
'url' => 'https://example.org/callback'
]
]
]
])
]
]
]);

guzzle 6 post does not work

I am trying to submit a post with JSON content. I always get this message back:
"Client
error: POST
https://sandbox-api-ca.metrc.com//strains/v1/create?licenseNumber=CML17-0000001
resulted in a 400 Bad Request response: {"Message":"No data was
submitted."}"
(All keys and license number are sandbox. I changed keys slightly so auth wont work. )
here is my code
public function metrc()
{
$client = new Client();
$url = 'https://sandbox-api-ca.metrc.com//strains/v1/create?licenseNumber=CML17-0000001';
$request = $client->post($url, [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['name' => "Spring Hill Kush"],
'auth' => ['kH-qsC1oJPzQnyWMrXjw0EQh812jHOX52ALfUIm-dyE3Wy0h', 'fusVbe4Yv6W1DGNuxKNhByXU6RO6jSUPcbRCoRDD98VNXc4D'],
]);
}
Your code is correct, it should works as expected. Seems that the issue is on the server side. Maybe the format of the POST request is not correct?
BTW, 'headers' => ['Content-Type' => 'application/json'] is unnecessary, Guzzle sets the header by itself automatically when you use json option.

JWT: Why am I always getting token_not_provided?

I am sending a PUT request to an API endpoint I have created. Using jwt, I am able to successfully register and get a token back.
Using Postman, my request(s) work perfectly.
I am using Guzzle within my application to send the PUT request. This is what it looks like:
$client = new \Guzzle\Http\Client('http://foo.mysite.dev/api/');
$uri = 'user/123';
$post_data = array(
'token' => eyJ0eXAiOiJKV1QiLCJhbGc..., // whole token
'name' => 'Name',
'email' => name#email.com,
'suspended' => 1,
);
$data = json_encode($post_data);
$request = $client->put($uri, array(
'content-type' => 'application/json'
));
$request->setBody($data);
$response = $request->send();
$json = $response->json();
} catch (\Exception $e) {
error_log('Error: Could not update user:');
error_log($e->getResponse()->getBody());
}
When I log the $data variable to see what it looks like, this is what is returned.
error_log(print_r($data, true));
{"token":"eyJ0eXAiOiJKV1QiL...","name":"Name","email":"name#email.com","suspended":1}
Error: Could not suspend user:
{"error":"token_not_provided"}
It seems like all data is getting populated correctly, I am not sure why the system is not finding the token. Running the "same" query through Postman (as a PUT) along with the same params works great.
Any suggestions are greatly appreciated!
The token should be set in the authorization header, not as a post data parameter
$request->addHeader('Authorization', 'Basic eyJ0eXAiOiJKV1QiL...');

refresh_token Invalid Credentials errors

I'm stumped. I'm trying to manually get a refresh token to load an access token for me on Mirror API using Perl and it keeps giving me credentials errors. When I load the exact HTTP request in the PHP example code (I've printed out the HTTP to compare) the same refresh_token works fine.
Here's my Perl HTTP request:
*POST https://accounts.google.com/o/oauth2/token
Host: accounts.google.com
User-Agent: libwww-perl/6.02
Content-Length: 175
Content-Type: application/x-www-form-urlencoded
client_id=client_id_goes_here&client_secret=client_secret_goes_here&refresh_token=refresh_token_goes_here&grant_type=refresh_token*
Here's the PHP on the same refresh_token:
*POST /o/oauth2/token HTTP/1.1
content-type: application/x-www-form-urlencoded
content-length: 175
client_id=client_id_goes_here&client_secret=client_secret_goes_here&refresh_token=refresh_token_goes_here&grant_type=refresh_token*
My Perl looks like this:
my $auth_response = $ua->request(POST 'https://accounts.google.com/o/oauth2/token',
'Host' => 'accounts.google.com',
'Content_Type' => 'application/x-www-form-urlencoded',
'Content' => [
'client_id' => $client_id,
'client_secret' => $client_secret,
'refresh_token' => $credentials->{'refresh_token'},
'grant_type' => 'refresh_token',
],
);
HELP! :-)
It looks like you're using LWP. I hacked up this quick example which uses LWP to dance the OAuth 2.0 dance with Google from start to token refresh.
Based on my experimentation, the code you've shown so far looks correct. Here's the exact code I used to refresh my access token:
my $auth_response = $ua->request(POST 'https://accounts.google.com/o/oauth2/token',
'Host' => 'accounts.google.com',
'Content_Type' => 'application/x-www-form-urlencoded',
'Content' => [
'client_id' => $client_id,
'client_secret' => $client_secret,
'refresh_token' => $refresh_token,
'grant_type' => 'refresh_token',
],
);
If you're still observing an error, try cloning that repo, populating your client_id and client_secret, and seeing if the problem persists. If it does, please share the result of print Dumper($auth_response); which will provide a lot of useful info.
Also, Perl isn't a language officially supported by Google, but it looks like the community has come through: there's an open source Perl client library. I've never used it before, but you may want to check it out.