Reading from the response stream reached the inactivity timeout - postman

trying to implement REST API oauth2.0 authentification with symfony4.
The road /oauth/v2/token works well but, i'm trying to create /api/login road that will get credentials from the request and make a Httpclient->request() to /oauth/v2/token and get the access token and return to the user.
This is my code :
public function login(Request $request)
{
//dd($request->getMethod());
$method = $request->getMethod();
$grantType = $request->query->get('grant_type');
$clientId = $request->query->get('client_id');
$secretId = $request->query->get('client_secret');
$username = $request->query->get('username');
$password = $request->query->get('password');
$path = $_SERVER['API_BASE_URL'] . 'oauth/v2/token';
$httpClient = HttpClient::create();
//dd($httpClient);
$response = $httpClient->request($method, $path, [
// these values are automatically encoded before including them in the URL
'query' => [
'grant_type' => $grantType,
'client_id' => $clientId,
'client_secret' => $secretId,
'username' => $username,
'password' => $password,
],
]);
$statusCode = $response->getStatusCode();
$contentType = $response->getHeaders()['content-type'][0];
$content = $response->getContent();
$content = $response->toArray();
return $content;
}
But i'm getting this error since and i'm unable to solve :
{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"Reading from the response stream reached the inactivity timeout.","class":"Symfony\\Component\\HttpClient\\Exception\\TransportException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":"D:\\vendor\\symfony\\http-client\\Chunk\\ErrorChunk.php","line":105,"args":[]},{"namespace":"Symfony\\Component\\HttpClient\\Chunk","short_class":"ErrorChunk","class":"Symfony\\Component\\HttpClient\\Chunk\\ErrorChunk","type":"->","function":"__destruct","file":"\\vendor\\symfony\\http-client\\Response\\CurlResponse.php","line":121,"args":[]},{"namespace":"Symfony\\Component\\HttpClient\\Response","short_class":"CurlResponse","class":"Symfony\\Component\\HttpClient\\Response\\CurlResponse","type":"::","function":"Symfony\\Component\\HttpClient\\Response\\{closure}","file":"\\vendor\\symfony\\http-client\\Response\\ResponseTrait.php","line":67,"args":[["object","Symfony\\Component\\HttpClient\\Response\\CurlResponse"]]},{"namespace":"Symfony\\Component\\HttpClient\\Response","short_class":"CurlResponse","class":"Symfony\\Component\\HttpClient\\Response\\CurlResponse","type":"->","function":"getStatusCode","file":"\\src\\Controller\\RestApiController.php","line":121,"args":[]},{"namespace":"App\\Controller","short_class":"RestApiController","class":"App\\Controller\\RestApiController","type":"->","function":"login","file":"D:\\Binghana\\new\\goldwin-website\\vendor\\symfony\\http-kernel\\HttpKernel.php","line":150,"args":[["object","Symfony\\Component\\HttpFoundation\\Request"]]},{"namespace":"Symfony\\Component\\HttpKernel","short_class":"HttpKernel","class":"Symfony\\Component\\HttpKernel\\HttpKernel","type":"->","function":"handleRaw","file":"\\vendor\\symfony\\http-kernel\\HttpKernel.php","line":67,"args":[["object","Symfony\\Component\\HttpFoundation\\Request"],["integer",1]]},{"namespace":"Symfony\\Component\\HttpKernel","short_class":"HttpKernel","class":"Symfony\\Component\\HttpKernel\\HttpKernel","type":"->","function":"handle","file":"D:\\Binghana\\new\\goldwin-website\\vendor\\symfony\\http-kernel\\Kernel.php","line":198,"args":[["object","Symfony\\Component\\HttpFoundation\\Request"],["integer",1],["boolean",true]]},{"namespace":"Symfony\\Component\\HttpKernel","short_class":"Kernel","class":"Symfony\\Component\\HttpKernel\\Kernel","type":"->","function":"handle","file":"D:\\Binghana\\new\\goldwin-website\\public\\index.php","line":25,"args":[["object","Symfony\\Component\\HttpFoundation\\Request"]]}]}]}}
I have tried updating httpclient version, even using Guzzle, same error.

Related

AWS - Guzzle The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method

I am using SignatureV4 aws authentication to authenticate my API call,
I am also using Guzzle/Client to call API.
By following these above, my API call works for GET method only and not working for POST method. For POST method call it show an error ( The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method )
My code :
use Aws\Credentials\CredentialProvider;
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
$request = new Request(
'POST',
'https://XXXXXXXXXXXXx.com/XXXXXx/XXXXXXx',
[
'body' => '{
"param1": "loream",
"param2": "4970",
"param3": "1",
"param4": "2.0",
"param5": "mL",
"param6": "kgs",
"param7": 0,
}'
]
);
$key['credentials'] = array(
'key' => 'XXXXXXXXXXXXXXX-access-key',
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-secret-key'
);
$credentials = call_user_func(CredentialProvider::defaultProvider(
$key
));
// Construct a request signer
$signer = new SignatureV4('execute-api',
'us-east-1'
);
// Sign the request
$request = $signer->signRequest($request, $credentials);
// Send the request
try {
$response = (new Client)->send($request);
print_r($response);
}
catch (Exception $exception) {
$responseBody = $exception->getResponse()->getBody(true);
echo $responseBody;
}
$response = (new Client)->send($request);
$results = json_decode($response->getBody());

AWS S3 Presigned POST to URL query string for curl

trying to generate a pre-signed query string to POST to an S3 bucket using the AWS SDK for PHP. Getting the following error:
The request signature we calculated does not match the signature you provided.
Here's the php file to generate the URL, adapted from here.
<?php
require('./aws/aws-autoloader.php');
$client = new \Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => '[KEY]',
'secret' => '[SECRET]',
],
]);
$bucket = '[mybucket]';
// Set some defaults for form input fields
$formInputs = ['acl' => 'public-read'];
// Construct an array of conditions for policy
$options = [
['acl' => 'bucket-owner-full-control'],
['bucket' => $bucket],
];
// Optional: configure expiration time string
$expires = '+2 hours';
$postObject = new \Aws\S3\PostObjectV4(
$client,
$bucket,
$formInputs,
$options,
$expires
);
// Get attributes to set on an HTML form, e.g., action, method, enctype
$formAttributes = $postObject->getFormAttributes();
// Get form input fields. This will include anything set as a form input in
// the constructor, the provided JSON policy, your AWS Access Key ID, and an
// auth signature.
$formInputs = $postObject->getFormInputs();
echo "https://[mybucket].s3.amazonaws.com/?".http_build_query($formInputs)."&X-Amz-Expires=7200&X-Amz-SignedHeaders=host";
?>
And the curl command:
curl --request POST --upload-file "file.gif" -k [query string here]

PHP authentication integration with WOS2 Identity Server

Actually, I have a CakePHP application that authenticates with SimpleSAML using WSO2 Identity Server (it redirects to WSO2IS login page). I need to create a page in my application and send the informations to WSO2IS to authenticate the user. How can I do it? I didn't found any example/documentation about it.
I followed this tutorial.
Files in simplesaml:
config/authsources.php
<?php
$config = array(
'wso2-sp' => array(
'saml:SP',
'entityID' => 'IntranetSP', // I supposed that it is the ID of my Service Provider
'idp' => 'https://soa.rw1.local:9443/samlsso'
)
);
?>
metadata/saml20-idp-remote.php
<?php
$metadata['https://soa.rw1.local:9443/samlsso'] = array(
'name' => array(
'en' => 'WSO2 IS',
'no' => 'WSO2 IS',
),
'description' => 'Login with WSO2 IS SAML2 IdP.',
'SingleSignOnService' => 'https://soa.rw1.local:9443/samlsso',
'SingleLogoutService' => 'https://soa.rw1.local:9443/samlsso',
'certFingerprint' => '6bf8e136eb36d4a56ea05c7ae4b9a45b63bf975d'
);
?>
In my Wso2 IS:
Service provider Configuration:
Service Provider Name: IntranetSP
Local & Outbound Authentication Configuration/Request Path Authentication Configuration: basic-auth
In your service provider configuration, under local and outbound authentication configuration, configure SP to use request path authentication.For more information about doing this, please follow this.
Following is a java code where you can send the request from a client.
#Test(alwaysRun = true, description = "Test login success")
public void testLoginSuccess() throws Exception {
HttpPost request = new HttpPost(TRAVELOCITY_SAMPLE_APP_URL + "/samlsso?SAML2.HTTPBinding=HTTP-POST");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", adminUsername));
urlParameters.add(new BasicNameValuePair("password", adminPassword));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
String samlRequest = "";
String secToken = "";
while ((line = rd.readLine()) != null) {
if (line.contains("name='SAMLRequest'")) {
String[] tokens = line.split("'");
samlRequest = tokens[5];
}
if (line.contains("name='sectoken'")) {
String[] tokens = line.split("'");
secToken = tokens[5];
}
}
EntityUtils.consume(response.getEntity());
request = new HttpPost(isURL + "samlsso");
urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("sectoken", secToken));
urlParameters.add(new BasicNameValuePair("SAMLRequest", samlRequest));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
response = client.execute(request);
String samlResponse = "";
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
if (line.contains("name='SAMLResponse'")) {
String[] tokens = line.split("'");
samlResponse = tokens[5];
}
}
Base64 base64Decoder = new Base64();
samlResponse = new String(base64Decoder.decode(samlResponse))
EntityUtils.consume(response.getEntity());
}
You should be able to achieve this in PHP by sending the same requests.
But if your requirement is to change the login page, you can customize wso2 IS login page as mentioned here without using your own page. If your requirement is this, I recommend you to do this as this will make your life much easier.

get content from facebook url using php

How to get content from facebook url and extract facebook user id and access token. I have used CURL and it's returning empty content.
$url = 'https://graph.facebook.com/oauth/access_token?client_id='.$fbconfig['appid'].'&redirect_uri='.$returnurl.'&client_secret='.$fbconfig['secret'].'&code='.$_REQUEST['code'];
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
curl_close($ch);
$iResult=AlowUserAccess();
$FBUserId = explode('|', $iResult);
$FBUserId = explode('|', $FBUserId['1']);
$FBUserId = explode('-', $FBUserId['0']);
$iUserId = $FBUserId['1'];
$iUserId = $iResult;
$sAccessToken = explode('access_token=', $iResult);
Try using the options used here:
PHP script to automate login and form submit
Your not setting both SSL opts, it is also possible they may want to set a cookie.

Facebook API - saving OAuth access token in session

I am trying to find a way to keep connected with the Facebook API once authorised using OAuth but am having problems. I dont want the users of my App to have to login via Facebook every time they want to use my app.
I store the oauth access toekn in a database after the user authenticates with facebook and I have "offline_access" permissions set, so in theory, this should be possible.
However, I get "Uncaught OAuthException: An active access token must be used to query information about the current user." when trying to connect to Facebook API using a saved Oauth token stored in a database.
header("p3p: CP=\"ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV\""); // hack to stop facebook wierd cookie problems
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secretid',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//get the user's access token
$access_token = $facebook->getAccessToken();
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$access_token = $result[0];
}
if($access_token) {
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me',
'GET',
array(
'access_token' => $access_token
)
);
//add to details database
//find the user by ID
if ($user != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, clientID, oauth_uid, username, oauth_token, oauth_secret) VALUES ('facebook', $clientID, $user, '{$accounts['name']}', '$access_token', '')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '$access_token', oauth_secret = '' WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
}
//save the information inside the session
$_SESSION['_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
}
$facebookAuth = TRUE;
Facebook pass an expires field when it pass your application the access token and default as per the Facebook is 2hours.
there are other factors why which a access_token can expire and here are the complete details for you
Ankur Pansari
How-To: Handle expired access tokens
Now next we can talk about offline_access which means
It Enables your app to perform authorized requests
on behalf of the user at any time. By default,
most access tokens expire after a short time period to ensure applications
only make requests on behalf of the user when the are actively
using the application. This permission makes the
access token returned by our OAuth endpoint long-lived.
So it all means you have to make sure you always using valid access_token.For details about various permission here is a reference link
Facebook Permissions