AWS Cognito Developer Authentication in PHP - php

Am trying to implement developer authentication using the PHP SDK but keep getting this error:
Fatal error: Uncaught
Aws\CognitoIdentity\Exception\CognitoIdentityException: AWS Error
Code: AccessDeniedException, Status Code: 400, AWS Request ID:
da162f98-fb50-11e4-937e-0bf2642a4752, AWS Error Type: client, AWS
Error Message: User: arn:aws:iam::256661818246:user/tester is not
authorized to perform:
cognito-identity:GetOpenIdTokenForDeveloperIdentity on resource:
arn:aws:cognito-identity:us-east-1:256661818246:identitypool/us-east-1:69767873-2de2-4cc7-a78f-3d18b5e9bf71,
User-Agent: aws-sdk-php2/2.8.3 Guzzle/3.9.3 curl/7.20.0 PHP/5.3.6
thrown in
/var/www/html/aws/Aws/Common/Exception/NamespaceExceptionFactory.php
on line 91
This is my sample code:
<?php
session_start();
//Include AWS client libs
require (dirname(__DIR__).'/aws/aws-autoloader.php');
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
/* Global Vars */
$aws_region = 'us-east-1';
$aws_key = '<AWS_KEY>';
$aws_secret = '<AWS_SECRET>';
$aws_account_id = '<AWS_ACCOUNT_ID>';
$identity_pool_id = 'us-east-1:xxxx-xxxx-xxxx-xxxx';
//Initialize a Cognito Identity Client using the Factory
$client = CognitoIdentityClient::factory(array('region' => $aws_region, 'key' => $aws_key, 'secret' => $aws_secret));
/* Acquire new Identity */
$identity = $client->getOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $identity_pool_id, 'Logins' => array('login.custom.traffic' => 'jkljkasdjk')));
//Obtain Identity from response data structure
$id = $identity->get('IdentityId');
echo "IdentityId: ".$id;
?>
I suspect the error occurs while trying to get the developer Identity. What am I missing?

Reason behind this error is there might be no policy attached to the IAM user 'tester'.
You can attach an already existing policy 'AmazonCognitoDeveloperAuthenticatedIdentities' from IAM console which gives this user access to Cognito APIs including 'getOpenIdTokenForDeveloperIdentity' as well.

Related

microsoft graph api to create online meeting programmatically but facing 403 error

I'm using Microsoft Graph Api (PHP->msGraph SDK) to create online meetings.
I'm Facing 403 error can someone help me out.
$clientId = "***********************************";
$clientSecret = "***********************************";
$tenantId = '***********************************';
$responseUri = "http://localhost:8888/moodle39";
$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;
//Create a new Graph client.
$graph = new Graph();
$graph->setAccessToken($accessToken);
$onlinemeet->startDateTime = "2020-09-02T14:30:34.2444915";
$onlinemeet->endDateTime = "2020-09-02T15:30:34.2444915";
$onlinemeet->subject = "Test Meeting";
$jso = json_encode($onlinemeet);
$user = $graph->createRequest("POST", "/me/onlineMeetings")->addHeaders(array("Content-Type" => "application/json"))->attachBody($jso)->setReturnType(User::class) ->execute();
Exception - Client error: POST https://graph.microsoft.com/beta/me/onlineMeetings resulted in a 403 Forbidden response: { "error": { "code": "Forbidden", "message": "", "innerError": { "request-id": "bd43aa57-511e-4 (truncated...)
While creating an application in azure portal
under API permission i gave permission to access
GraphApi->Delegated Permissions->onlinemeetings.ReadWrite.
Can someone help me with a proper example or proper syntax in PHP.
Thankyou !!..
You cannot use the client credential flow to get the token to call the /me endpoint. For the client credential flow, it is usually used for server-to-server interactions that must run in the background and do not interact with the user immediately(No user logged in). For the /me endpoint, it is usually User login is required, so you should use auth code flow.
By the way, APIs under the /beta version in Microsoft Graph are subject to change. Use of these APIs in production applications is not supported. Therefore, it is recommended that you use the /v1.0 version.
please see:here.
Update:
There are many similar samples, I hope they can help you:
OAuth 2.0 PHP Sample Code.
Authentication and Authorization Using Auth0 in PHP.

TheNetworg oAuth2 to Microsoft Graph reports token expired while it's not

I am trying to build a simple MS Graph API call to get familiar with Graph.
However, I can't get it to work. MS Graph keeps giving the error that my token has expired, while it's not.
Code:
<?php
require_once('C:\inetpub\site6\vendor\autoload.php');
// Using newest version of TheNetworg Oauth2
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
'clientId' => '***************',
'clientSecret' => '**********',
'redirectUri' => 'https://app2.***/test.php'
]);
// Set to use v2 API, skip the line or set the value to Azure::ENDPOINT_VERSION_1_0 if willing to use v1 API
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;
$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
//echo $baseGraphUri;
$provider->tenant = '*********.onmicrosoft.com'; //Azure AD ID
$provider->authWithResource;
$provider->scope = $baseGraphUri . '/.default';
$token = $provider->getAccessToken('client_credentials', ['scope' => $provider->scope]);
// echo $token;
// Set up our request to the API
$ref= 'users/someuser#mytenant.com';
$response = $provider->get($ref, $token, $headers = []);
// Store the result as an object
$result = json_decode( $response->getBody() );
?>
But I keep getting ended up with error:
PHP Fatal error: Uncaught
League\OAuth2\Client\Provider\Exception\IdentityProviderException:
Your access token has expired. Please renew it before submitting the
request. in
C:\inetpub\site6\vendor\thenetworg\oauth2-azure\src\Provider\Azure.php:394
What am I doing wrong? When I google the error, I get a lot of results telling that I am trying to access MS Graph with an Azure AD Graph token, but when I do echo $baseGraphUri; I really tells me graph.microsoft.com.
I found out what the error is. Although I use "$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);", the library still connects to the Azure AD API instead of the Microsoft Graph API. So it authenticates with the wrong kind (aud) of token.
Adding this line fixed the problem:
$provider->urlAPI = 'https://graph.microsoft.com/';

QuickBooks-V3-PHP-SDK only working partially (with QuickBooks Online)

The QuickBooks-V3-PHP-SDK is giving me a hard time.
I'm trying to use it to sync invoice data. I can successfully get authorization using OAuth 2.0 and connect my client PHP web application to QuickBooks Online. However, while I can successfully make a getCompanyInfo call and receive the results, I can't make a getUserInfo call (or most of the other API calls for that matter), as it will complain about the "access token object" not being set yet.
While connecting to QuickBooks and getting authorization, everything seems to work accurately - and the access token object is successfully placed in the PHP Session. But for some reason, it complains when I try to get the UserInfo data, or use any of the other API calls.
Here's the error that I receive:
Fatal error: Uncaught QuickBooksOnline\API\Exception\SdkException: [0]: Can't get OAuth 2 Access Token Object. It is not set yet.
thrown in /compiled/src/Core/OAuth/OAuth2/OAuth2LoginHelper.php on line 129
Here's how I try to get the UserInfo:
$dataService->updateOAuth2Token($accessToken);
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
Again, getting the CompanyInfo works without any problems.
Does anyone have any idea what's going on?
Below I'm including the code from apiCall.php (from the HelloWorld example package, further edited by myself). This file is used to make requests through Ajax after I already connected to and received authorization from QuickBooks Online.
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use QuickBooksOnline\API\Core\ServiceContext;
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Facades\Invoice;
session_start();
function makeAPICall()
{
// Create SDK instance
$config = include('config.php');
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $config['client_id'],
'ClientSecret' => $config['client_secret'],
'RedirectURI' => $config['oauth_redirect_uri'],
'scope' => $config['oauth_scope'],
'baseUrl' => "development"
));
/*
* Retrieve the accessToken value from session variable
*/
$accessToken = $_SESSION['sessionAccessToken'];
$dataService->throwExceptionOnError(true);
/*
* Update the OAuth2Token of the dataService object
*/
$dataService->updateOAuth2Token($accessToken);
//Get the requested data:
$action = filter_input(INPUT_GET, "action", FILTER_SANITIZE_SPECIAL_CHARS);
$method = "get$action";
switch($action){
case "CompanyInfo":
$result = $dataService->$method();
break;
case "UserInfo":
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$result = $OAuth2LoginHelper->getUserInfo();
break;
case "InvoiceExample":
$allInvoices = $dataService->Query("SELECT * FROM Invoice");
$result = $allInvoices;
break;
}
var_dump($result);
return $result;
}
$result = makeAPICall();
?>
Anyone any idea what I'm doing wrong?
The Intuit (QuickBooks) support team provided the answer to me. In my ApiCall code above, I had to use the following code to make the UserInfo request:
$result = $OAuth2LoginHelper->getUserInfo($accessToken->getAccessToken(), 'development');
Obviously, if this would involve production keys, I would have to replace 'development' with 'production'.

Fatal error code 401 when connecting to Cloud Datastore

I am trying to connect to Google Cloud Datastore, using the code below. I have tried to follow these quidelines as well as these. I am using Composer and my code is in a Wordpress plugin. I have put my credentials file in the same folder as the script and it is found.
<?php # -*- coding: utf-8 -*-
/*
* Plugin Name: Cloud Datastore Connection
*/
add_shortcode( 'cd_connect', 'cloud_datastore_connection' );
use Google\Cloud\Core\ServiceBuilder;
use Google\Cloud\Datastore\DatastoreClient;
function cloud_datastore_connection( $attributes )
{
// For Composer
require 'vendor/autoload.php';
// Authenticate using keyfile data
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('/www/.../XXX.json'), true)
]);
$datastore = new DatastoreClient(['projectId' => 'ultunaphotons']);
// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = 'bob#example.com';
$datastore->insert($bob);
// Update the entity
$bob['email'] = 'bobV2#example.com';
$datastore->update($bob);
// testing
print bob['email'];
}
?>
I get this error message:
Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {
"error": { "code": 401, "message": "Request is missing required
authentication credential. Expected OAuth 2 access token, login cookie
or other valid authentication credential. See
https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED" } } in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php:362
Stack trace: #0
/www/.../vendor/google/cloud-core/src/RequestWrapper.php(206): Google\Cloud\Core\RequestWrapper->convertToGoogleException(Object(GuzzleHttp\Exception\ClientException)) #1 /www/.../vendor/google/cloud-core/src/RestTrait.php(95):
Google\Cloud\Core\RequestWrapper->send(Object(GuzzleHttp\Psr7\Request),
Ar in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php
on line 362
Any ideas what I'm doing wrong?

woocommerce api v2 returns uncaught exception

Using wc-api (https://github.com/woocommerce/wc-api-php)
My client function: (literally the same as in docs)
$woocommerce = new Client(
$store_url, // Your store URL
$consumer_key, // Your consumer key
$consumer_secret, // Your consumer secret
[
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v2', // WooCommerce WP REST API version
'query_string_auth' => true // Force Basic Authentication as query string true and using under HTTPS
]
);
and when I try with
$results = $woocommerce->get('');
or
$results = $woocommerce->get('products');
or any other endpoint it gives me:
An uncaught Exception was encountered
Type: Automattic\WooCommerce\HttpClient\HttpClientException
Message: Error: No route was found matching the URL and request method
[rest_no_route]
If I change the version to 'wc/v1' it is working ok.
Do I need to add some other plugins or additional code to make v2 work?
Try send your request like this, with your creds in param :
$res = ($woocommerce->get('orders?status=processing&consumer_key=ck_XXXXXXXXXXXXXXXXXXXXXXXXX&consumer_secret=cs_XXXXXXXXXXXXXXXXXXXXXXXXX'));

Categories