Webklex\PHPIMAP Modern Auth Not Working 365 - oauth-2.0

As with most people, Microsoft are turning off basic authentication. This means we need to use Modern Auth to retrieve emails from a mailbox.
However,when we retrie the access token fails with "
Client error: `POST https://login.microsoftonline.com/aea9a7d8-73fb-41af-987b-6fe14277421e/oauth2/v2.0/token` resulted in a `400 Bad Request` response:\n
{"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '\"014438b9-82dc-4a4c-9584 (truncated...)
"
Here is the code we have for retrieving and connecting to IMAP. I am passing actual email and password in usename and password field
/* Get the access Token */
$Secret = '**REMOVED**';
$AppID = '**REMOVED**';
$TenantID = '**REMOVED**';
$AccessToken = '';
try {
$guzzle = new \GuzzleHttp\Client(['headers' => ['User-Agent' => 'App-Token-Request']]);
$url = 'https://login.microsoftonline.com/'.$TenantID.'/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'grant_type' => 'password',
'client_id' => $AppID,
'client_secret' => $Secret,
'scope' => 'https://graph.microsoft.com/.default', //'https://outlook.office365.com/IMAP.AccessAsUser.All',// 'https://graph.microsoft.com/.default',
'username' => '**REMOVED**',
'password' => '**REMOVED**',
],
])->getBody()->getContents());
$this->info(var_dump($token));
$AccessToken = $token->access_token;
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
dd($e);
return redirect('/')->with('error', 'Error requesting access token')->with('errorDetail', json_encode($e->getResponseBody()));
}

Related

How to Authenticate Google youtube api with ruby, Signet , google api gem?

ERROR: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
My code :
#client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://oauth2.googleapis.com/token',
:client_id => ENV['GMB_CLIENT_ID'],
:client_secret => ENV['GMB_CLIENT_SECRET'],
:scope => 'https://www.googleapis.com/auth/youtube.upload',
:redirect_uri => 'https://localhost:4200/youtube'
)
# a = my user with token and refresh token got from signet oAuth with google
response = {
"access_token" => a.token,
"refresh_token" => a.refresh_token,
"expries_in" => total_second,
"scope" => "https://www.googleapis.com/auth/youtube.upload",
"token_type" => "Bearer"
}
#client.update!(response)
#service ||= Google::Apis::YoutubeV3::YouTubeService.new
#service.key = "my key"
#service.authorization = #client #setting the authorization for api
status = Google::Apis::YoutubeV3::VideoStatus.new(
privacy_status: 'unlisted',
)
snippet = Google::Apis::YoutubeV3::VideoSnippet.new(
title: "My video",
description: "description",
)
video_object = Google::Apis::YoutubeV3::Video.new(
status: status,
snippet: snippet,
)
#service.insert_video(
'id,snippet,status',
video_object,
notify_subscribers: true,
content_type: 'video/webm',
options: { authorization: #client }
)
Help needed to make it work. Authentication is not working

I can't reach customers AdWords Account with Google Login

I want to connect -any- customer Google AdWords Account with Google Login. (Like Wordstream)
I prepared a code, but there is a problem somewhere, I can't run it.
When the customer press the connect button, the screen appears. It says "XXX wants to acces your Google Account", it is approved but I cannot receive data.
How can i get datas from customer's account?
Code:
require 'google-api/vendor/autoload.php';
use Google\Auth\OAuth2;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
session_start();
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => 'https://xxxxx.xxxxxx',
'clientId' => 'xxxxxxxxx.apps.googleusercontent.com',
'clientSecret' => 'xxxxxxxxxxx',
'scope' => 'https://www.googleapis.com/auth/adwords',
'refresh_token' => 'xxxxxxxxxx'
]);
if(!isset($_GET['code'])){
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
$config = [
'access_type' => 'offline',
'prompt' => 'consent',
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])){
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
$refreshToken = $authToken['refresh_token'];
$path = "xxxxx/google-api/vendor/adsapi_php.ini";
$session = (new AdWordsSessionBuilder())
->fromFile($path)
->withOAuth2Credential($oauth2)
->build();
$adWordsServices = new AdWordsServices();
$campaignService = $adWordsServices->get($session, CampaignService::class);
print_r($campaignService);
}

Xero-Api PHP Authentication Unsuccessful when refreshing token

I am having issues with refreshing tokens with the xero api. When I first create the token, everything is fine. When I refresh the token, I get authentication unsuccessful.
{"Type":null,"Title":"Forbidden","Status":403,"Detail":"AuthenticationUnsuccessful","Instance":"8d6256e5-3376-4960-be52-cf8b22ee241c","Extensions":{}}
My code is as follows:
public function refreshToken()
{
$provider = new GenericProvider([
'clientId' => $valuestore->get('client_id'),
'clientSecret' => $valuestore->get('client_secret'),
'redirectUri' => $valuestore->get('callback_url'),
'urlAuthorize' => 'https://login.xero.com/identity/connect/authorize',
'urlAccessToken' => 'https://identity.xero.com/connect/token',
'urlResourceOwnerDetails' => 'https://api.xero.com/api.xro/2.0/Organisation'
]);
$newAccessToken = $provider->getAccessToken('refresh_token', [
'refresh_token' => $this->getRefreshToken()
]);
// Save my token, expiration and refresh token
$this->setOauth($newAccessToken);
}
public function setOauth($accessToken)
{
$oauth2 = [
'token' => $accessToken->getToken(),
'expires' => $accessToken->getExpires(),
'tenant_id' => $this->getTenantId(),
'refresh_token' => $accessToken->getRefreshToken(),
'id_token' => $accessToken->getValues()["id_token"]
];
//set session
}
Thanks in advance
Regards
Danny

SOAP Ruby On Rails logon Affili.net

I try to logon Affili.net via SOAP by using the savon-gem.
client = Savon.client do
wsdl "https://api.affili.net/V2.0/Logon.svc?wsdl"
end
message = {
'Username' => '123123',
'Password' => '123123',
'ins2:WebServiceType' => 'Publisher' }
response = client.call(:logon, :message => message)
But I only get this exception:
(a:DeserializationFailed) The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://affilinet.framework.webservices/Svc:LogonRequestMsg. The InnerException message was 'Error in line 1 position 777. 'EndElement' 'LogonRequestMsg' from namespace 'http://affilinet.framework.webservices/Svc' is not expected. Expecting element 'Username | Password | WebServiceType'.'. Please see InnerException for more details.
https://developer-api.affili.net/V2.0/Logon.svc?wsdl
Whats wrong?
Update
Now i tried some tools like this:
http://www.soapclient.com/soapclient?template=%2Fclientform.html&fn=soapform&SoapTemplate=%2FSoapResult.html&SoapWSDL=https%3A%2F%2Fdeveloper-api.affili.net%2FV2.0%2FLogon.svc%3Fwsdl&_ArraySize=2
And it also tells me: it does not work. But my Account and that credentials are ok!
So I tried it on PHP
define ("WSDL_LOGON", "https://api.affili.net/V2.0/Logon.svc?wsdl");
define ("WSDL_STATS", "https://api.affili.net/V2.0/PublisherStatistics.svc?wsdl");
$Username = '123123'; // the publisher ID
$Password = '123123'; // the publisher web services password
$SOAP_LOGON = new SoapClient(WSDL_LOGON);
$Token = $SOAP_LOGON->Logon(array(
'Username' => $Username,
'Password' => $Password,
'WebServiceType' => 'Publisher'
));
echo $Token;
and it works!
Whats the difference between all online tools, all offline tools and Ruby on Rails and PHP?
Try to send message with symbolized keys, like this:
message = {
logon: {
username: '123123',
password: '123123',
web_service_type: 'Publisher'
}
}
I still do not know the difference between the savon (2.7.2) and the PHP implementation.
But there is a solution for affili.net by using savon 3 (but it is not stable yet!)
client = Savon.new("https://api.affili.net/V2.0/Logon.svc?wsdl")
logon_body = {
LogonRequestMsg: {
'Username' => '123123',
'Password' => '123123',
'WebServiceType' => 'Publisher'
}
}
operation = client.operation('Authentication', 'DefaultEndpointLogon', 'Logon')
operation.body = logon_body
response = operation.call
puts response.body[:credential_token]
Some Savon 3 Documentation: http://savonrb.com/version3/getting-started.html
And the github branch: https://github.com/savonrb/savon/tree/version3

Delicious PHP oAuth Yahoo SDK Add Bookmark

I'm really having a difficult time trying to find a way to successfully authenticate a user and post a bookmark to their delicious account.
I downloaded Yahoo's YOS Social SDK then began modifying the oauth sampleapp.php. It basically handles the oAuth process by creating a login link that sends you to Yahoo to grant permission then sends you back to the callback URL you specify.
My thought was to modify the sampleapp.php file to make a request to delicious posts/add API to add a new bookmark once they oAuth process is over, but I'm running into some problems. I think I'm handling the POST request in the wrong manner.
Here is my code:
<?php
require dirname(__FILE__).'/lib/Yahoo.inc';
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', true);
YahooLogger::setDebug(true);
YahooLogger::setDebugDestination('LOG');
ini_set('session.save_handler', 'files');
session_save_path('/tmp/');
session_start();
define('OAUTH_CONSUMER_KEY', '<YOURS_GOES_HERE>');
define('OAUTH_CONSUMER_SECRET', '<YOURS_GOES_HERE>');
define('OAUTH_DOMAIN', '<YOURS_GOES_HERE>');
define('OAUTH_APP_ID', '<YOURS_GOES_HERE>');
if(array_key_exists("logout", $_GET)) {
YahooSession::clearSession();
header("Location: sampleapp.php");
}
$hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
if($hasSession == FALSE) {
$callback = YahooUtil::current_url();
$auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback);
}
else {
$session = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);
if($session) {
$consumer = new stdclass();
$consumer->key = OAUTH_CONSUMER_KEY;
$consumer->secret = OAUTH_CONSUMER_SECRET;
$nativeSession = new NativeSessionStore();
$token = $nativeSession->fetchAccessToken();
$client = new OAuthClient($consumer, $token, OAUTH_PARAMS_IN_HEADERS, OAUTH_SIGNATURE_HMAC_SHA1);
$request_url = 'http://api.del.icio.us/v2/posts/add';
$bookmark_url = 'http://www.tegdesign.com';
$parameters = array("url" => urlencode($bookmark_url), "description" => "test");
$response = $client->post($request_url,'TEXT',$parameters);
echo '<pre>';
print_r($response);
echo '</pre>';
}
}
if($hasSession == FALSE) {
echo sprintf("Login\n", $auth_url);
} else if($hasSession) {
echo "<p>Logout</p>";
}
?>
And here is the output of $response variable:
Array
(
[method] => POST
[url] => http://api.del.icio.us/v2/posts/add
[code] => 401
[requestHeaders] => Array
(
[0] => Accept: application/json
[1] => Authorization: OAuth realm="yahooapis.com",oauth_version="1.0",oauth_nonce="<MINE_SHOWS_HERE>",oauth_timestamp="1289407587",oauth_consumer_key="<MINE_SHOWS_HERE>",oauth_token="<MINE_SHOWS_HERE>",oauth_signature_method="HMAC-SHA1",oauth_signature="<MINE_SHOWS_HERE>"
[2] => Content-Type: TEXT
)
[requestBody] => Array
(
[url] => http%3A%2F%2Fwww.tegdesign.com
[description] => test
)
[responseHeaders] => Array
(
[Date] => Wed, 10 Nov 2010 16:46:32 GMT
[WWW-Authenticate] => OAuth oauth_problem="signature_invalid", realm="yahooapis.com"
[Content-Type] => application/json
[Cache-Control] => private
[Age] => 0
[Transfer-Encoding] => chunked
[Connection] => keep-alive
[Server] => YTS/1.17.21
)
[responseBody] => {"error":{"lang":"en-US","description":"Please provide valid credentials"}}
)
Does anybody have knowledge on using Delicious new API to successfully authenticate and post a bookmark on behalf a user? I'm having a terrible time.
Thanks,
Tegan
Set your content type to "application/x-www-form-urlencoded" instead of 'Text' on the below line.
$response = $client->post($request_url,'TEXT',$parameters);

Resources