Invalid grant error for free Office accounts - azure-active-directory

Are free Office accounts supported by Azure AD?
I've tried authenticating with two different accounts, one that has a monthly Office 365 subscription, and another free account that I created today.
I also have set up Microsoft sample users, and these are all working fine. But whenever I try to log into Outlook or OneDrive from my integration with either of the two accounts I mentioned above, authentication fails.
I can't find anything in the documentation that explains which types of accounts are not supported.
Any help will be greatly appreciated.
*UPDATE
On logging in with both accounts, these are the results:
Account with monthly subscription:
Auth code: M.R3_BAY.c531716c-c315-0c1e-7113-8805ab255856
Error message:
array(7) {
["error"]=>
string(13) "invalid_grant"
["error_description"]=>
string(199) "AADSTS9002313: Invalid request. Request is malformed or invalid.
Trace ID: 2e92a737-9d9a-4f2f-bbd1-17d231c5d701
Correlation ID: e6ca5e4a-2a62-4a6d-a556-9a1de111d41d
Timestamp: 2020-11-30 23:16:41Z"
["error_codes"]=>
array(1) {
[0]=>
int(9002313)
}
["timestamp"]=>
string(20) "2020-11-30 23:16:41Z"
["trace_id"]=>
string(36) "2e92a737-9d9a-4f2f-bbd1-17d231c5d701"
["correlation_id"]=>
string(36) "e6ca5e4a-2a62-4a6d-a556-9a1de111d41d"
["error_uri"]=>
string(52) "https://login.microsoftonline.com/error?code=9002313"
}
Free account:
Auth code: M.R3_BAY.6a128cd9-cb99-ee82-eafd-2934f94aa739
Error message:
array(7) {
["error"]=>
string(13) "invalid_grant"
["error_description"]=>
string(199) "AADSTS9002313: Invalid request. Request is malformed or invalid.
Trace ID: 285534b9-2f12-43ba-9af5-6aecf8d12302
Correlation ID: 66e71cee-aee8-42e9-8744-c470a6037767
Timestamp: 2020-11-30 23:17:02Z"
["error_codes"]=>
array(1) {
[0]=>
int(9002313)
}
["timestamp"]=>
string(20) "2020-11-30 23:17:02Z"
["trace_id"]=>
string(36) "285534b9-2f12-43ba-9af5-6aecf8d12302"
["correlation_id"]=>
string(36) "66e71cee-aee8-42e9-8744-c470a6037767"
["error_uri"]=>
string(52) "https://login.microsoftonline.com/error?code=9002313"
}
*UPDATE 2
This is the request:
$postUrl = "/common/oauth2/token";
$hostname = "login.microsoftonline.com";
$headers = array(
"POST " . $postUrl . " HTTP/1.1",
"Host: " . $hostname,
"Content-type: application/x-www-form-urlencoded",
);
$access_params = array(
"resource" => "https://graph.microsoft.com",
"grant_type" => "authorization_code",
"code" => $authority,
"client_id" => {clientid},
"client_secret" => {secret},
// "scope" => "offline_access calendars.readwrite",
"scope" => "https://graph.microsoft.com/.default",
// "roles" => "https://graph.microsoft.com/.default",
"redirect_uri" => {redirecturi}
);
$url = 'https://login.microsoftonline.com/common/oauth2/token';
$ch = curl_init("https://login.microsoftonline.com/common/oauth2/token HTTP/1.1");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $access_params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("application/x-www-form-urlencoded"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
$response = curl_exec($ch);

Related

Trying to figure out how to interface with the PayGate API

I can see that these are the parameters required when I make a call to the payment gateway API, but I have no idea how I would implement this in Javascript (specifically React). Any translators able to lend a hand?
Here is the example code in PHP:
$encryptionKey = 'secret';
$DateTime = new DateTime();
$data = array(
'PAYGATE_ID' => 10011072130,
'REFERENCE' => 'pgtest_123456789',
'AMOUNT' => 3299,
'CURRENCY' => 'ZAR',
'RETURN_URL' => 'https://my.return.url/page',
'TRANSACTION_DATE' => $DateTime->format('Y-m-d H:i:s'),
'LOCALE' => 'en-za',
'COUNTRY' => 'ZAF',
'EMAIL' => 'customer#paygate.co.za',
);
$checksum = md5(implode('', $data) . $encryptionKey);
$data['CHECKSUM'] = $checksum;
$fieldsString = http_build_query($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, 'https://secure.paygate.co.za/payweb3/initiate.trans');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I have been trying to use axios to make the request, but any method will do. I was trying to create an axios instance like so:
export default axios.create({
baseURL: 'https://secure.paygate.co.za/payweb3/initiate.trans',
headers:{
//I guess this is where PAYGATE_ID etc would go, but I'm not sure how to format it
}
})```
For React, the way to handle this is to generate an MD5 checksum and append it to the payload before sending, probably using CryptoJS or something. I created this function to generate the MD5:
const generateMD5 = (obj, secret = 'paygateSecret') => {
let str = ''
for (let val in obj){
str += obj[val]
}
str += secret
return CryptoJS.MD5(str).toString()
}
I have an object that contains my data:
var data = {
PAYGATE_ID: 10011072130,
REFERENCE: ref,
AMOUNT: amount,
CURRENCY: 'ZAR',
RETURN_URL: window.location.href,
TRANSACTION_DATE: new Date().toISOString(),
LOCALE: 'en-za',
COUNTRY: 'ZAF',
EMAIL: email,
}
Please note the order. It is very important.
Then, I generate the checksum using:
const CHECKSUM = generateMD5(data)
And then make the axios call:
axios.post('https://secure.paygate.co.za/payweb3/initiate.trans', { ...data, CHECKSUM }).then(...).catch(...)
I think this should work!

Sending JSON HTTP request using Guzzle HTTP: Result parameters are not as expected

I want to send a JSON request to an endpoint but the results that I get don't match the parameters requested.
This is the array
$datas = [
"institutionCode" => $institutionCode,
"brivaNo" => $brivaNo,
"custCode" => $custCode
];
This is the response using Guzzle HTTP
try {
$response = $client->request($verb, $endpoint,
[
"headers" =>
[
"Authorization" => "Bearer " . $token,
"BRI-Timestamp" => $timestamp,
"BRI-Signature" => $signature,
],
"json" => $datas
]
);
return $response;
}
catch (\GuzzleHttp\Exception\RequestException $e) {
return $e->getResponse();
}
This is the response from the endpoint
{
"status": false,
"errDesc": "Institution Code Tidak Boleh Kosong",
"responseCode": "03",
"data": {
"{\"institutionCode\":\"J104408\",\"brivaNo\":\"77777\",\"custCode\":\"7878787878\"}": ""
}
}
Why does the "data" not match the data array I have given above and instead creates a new pattern with a backslash in it?
This is the native way using cURL PHP
if there is someone can turn it into a Guzzle Http, it will help me,
after I tried this code, it also didn't help at all
$institutionCode = "J104408";
$brivaNo = "77777";
$custCode = "123456789115";
$payload = "institutionCode=".$institutionCode."&brivaNo=".$brivaNo."&custCode=".$custCode;
$path = "/v1/briva";
$verb = "DELETE";
$base64sign = generateSignature($path,$verb,$token,$timestamp,$payload,$secret);
$request_headers = array(
"Authorization:Bearer " . $token,
"BRI-Timestamp:" . $timestamp,
"BRI-Signature:" . $base64sign,
);
$urlPost ="https://sandbox.partner.api.bri.co.id/v1/briva";
$chPost = curl_init();
curl_setopt($chPost, CURLOPT_URL,$urlPost);
curl_setopt($chPost, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($chPost, CURLOPT_POSTFIELDS, $payload);
curl_setopt($chPost, CURLINFO_HEADER_OUT, true);
curl_setopt($chPost, CURLOPT_RETURNTRANSFER, true);
$resultPost = curl_exec($chPost);
$httpCodePost = curl_getinfo($chPost, CURLINFO_HTTP_CODE);
curl_close($chPost);
$jsonPost = json_decode($resultPost, true);
return $jsonPost;

file_get_contents gives error in codeigniter

$scope.formatfilename = response.fileformat[0].FileName;
// it contains filename = abcd
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);
it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.
how to solve in codeigniter ??
Option 1:
change in php.ini
allow_url_fopen = On
Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $siteaddr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
Working Example
<?php
$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
echo "<pre>", print_r($output), "</pre>";
die();
?>
Output
stdClass Object
(
[error_message] => The provided API key is invalid.
[results] => Array
(
)
[status] => REQUEST_DENIED
)

AJAX post request to third party REST api

. I am using laravel backend as API and angular as frontend which calls laravel api. Laravel api access the teamwork api through basic authentication using curl.
Now I am working with teamwork Api. Trying to create a comment using the API.
API documentation describes following.
{
"comment": {
"body": "Reply to earlier comment",
"notify": "",
"isprivate": false,
"pendingFileAttachments": "",
"content-type": "TEXT"
}
}
//ref : http://developer.teamwork.com/comments#creating_a_commen
in my ajax call i have used following
var data = $.param({
'body' : commentBodyValue, //variable
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
My post does not give error, but it also do not create a new comment too. What am I missing? I think i failed to arrange data according to the format allowed in api. Can you kindly help me to fix it?
Edit:
Angular Controller:
//add new comment
$scope.addComment = function(taskId,commentAuthorId)
{
var commentBod = document.getElementById("commentBody");
var commentBodyValue = commentBod.value;
console.log("new comment : "+ taskId + commentBodyValue);
//submit the post request
//$http.post();
//using jquery function param to serialize
var data = $.param({
'body' : commentBodyValue,
'notify': "",
'isPrivate':false,
"pendingFileAttachments": "",
"content-type": "TEXT"
});
var config = {
headers : {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
var url = "http://abounde.com/portal/api/post_comment/"+taskId;
$http.post(url,data,config)
.then(
function(response){
//success
console.log("response : Submitted :D " + response);
},
function(response){
//failure
console.log(response);
}
);
}
Edit 2
Laravel route and controller
Routes:
//post comment to resource
Route::post('post_comment/{task_id}',[
'uses'=>'PortalController#postComment',
'as'=>'portal.client.postComment'
]);
Controller:
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json");
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}
EDIT 3: Contacted with teamwork Api support.
After their advice i came up with following code
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
// $comment['body']=$request->input('body');
// $comment['notify']=$request->input('notify');
// $comment['isprivate']=$request->input('isprivate');
// $comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
// $comment['content-type']=$request->input('content-type');
$comment['comment']['body']="test";
$comment['comment']['notify']="";
$comment['comment']['isprivate']=false;
$comment['comment']['pendingFileAttachments']="";
$comment['comment']['content-type']="text";
$this->callTeamworkPostApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
//var_dump($comment);
//return response()->json(['response'=>"Trying"]);
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
}
///
public function callTeamworkPostApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
var_dump($msg);
//return response()->json(['res'=>$msg]);
}
var_dump($comment) gives
string(107) "{"comment":{"body":"test","notify":"","isprivate":false,"pendingFileAttachments":"","content-type":"text"}}"
However the api still do not save the comment. It has to be a curl post method issue. Right?
Edit 4:
I have done a var_dump(curl_getinfo($channel));
this gave me following response.
array(26) { ["url"]=> string(55) "http://projects.abounde.com/tasks/8199861/comments.json" ["content_type"]=> NULL ["http_code"]=> int(500) ["header_size"]=> int(229) ["request_size"]=> int(311) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.5) ["namelookup_time"]=> float(0) ["connect_time"]=> float(0.109) ["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(107) ["size_download"]=> float(0) ["speed_download"]=> float(0) ["speed_upload"]=> float(214) ["download_content_length"]=> float(0) ["upload_content_length"]=> float(107) ["starttransfer_time"]=> float(0.5) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "23.23.184.208" ["certinfo"]=> array(0) { } ["primary_port"]=> int(80) ["local_ip"]=> string(11) "192.168.0.6" ["local_port"]=> int(31657) }
The response code 500 may points to the fact that teamwork has some kind of internal issues.
The issue i found out is that you are not passing your comment data which you received from the frontend to the curl the request in callTeamworkApi().Try below code and see if you get your desired output or not
//post comment at task
public function postComment(Request $request, $task_id)
{
$secretApiKey = $request->session()->get('secretApiKey');
if(!empty($secretApiKey)){
//post the msg
$comment=array();
$comment['body']=$request->input('body');
$comment['notify']=$request->input('notify');
$comment['isPrivate']=$request->input('isprivate');
$comment['pendingFileAttachments']=$request->input('pendingFileAttachments');
$comment['content-type']=$request->input('content-type');
$this->callTeamworkApi($secretApiKey,"tasks/".$task_id."/comments.json",json_encode($comment));
}else{
return response()->json(['response'=>"Not Logged In"]);
}
}
//authentication method
public function callTeamworkApi($secretApiKey, $apiCallString,$comment)
{
//cURL
$password = "xxx";
$channel = curl_init();
//options
curl_setopt($channel, CURLOPT_URL, "http://projects.abounde.com/".$apiCallString); // projects.json?status=LATE gets all late projects
curl_setopt($channel, CURLOPT_HTTPHEADER,
array(
"Authorization: Basic " . base64_encode($secretApiKey . ":" . $password)
));
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($channel, CURLOPT_POSTFIELDS, $comment);
$msg = curl_exec($channel);
curl_close($channel);
return response()->json(['res'=>$msg]);
}
Solution Found:
While calling to the teamwork API, it is essential that the content-type is set to Json. and the information should be in header file. header variable should be a multi array which takes authentication and content type information.
$headers = array();
$headers[] = "Authorization: Basic " . base64_encode($secretApiKey . ":" . $password);
$headers[] = "Content-Type: application/json";
//pass it as variable
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
And then it works like charm.
returns following after creation of the comment.
{"commentId":"4294639","STATUS":"OK"}

trying to get information from urls array using cURL, getting bad request

my urls array contains like 100 urls, and is getting the information from an API designed for something like that.
Anyway, like 50% of the urls returns
400 Bad Request
Your browser sent a request that this server could not understand.
GET /player/euw/Wolves Deficio/ingame HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1
Host: api.captainteemo.com
Accept: */*
the urls are 100% correct, cause when I copy them to my browser, I DO get the info.
Here is my code:
function get_data($urls) {
// spoofing FireFox 2.0
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
if(is_array($urls)) {
$output = array();
foreach($urls as $url) {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
array_push($output, curl_exec($ch));
}
}
else {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $urls);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
}
I added CURLOPT_FOLLOWLOCATION in a case of redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Try this:
<?php
function get_data($urls)
{
if ( !is_array( $urls ) )
$urls = array( '0' => $urls );
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = array();
foreach($urls as $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
$output[$url] = curl_exec($ch);
}
curl_close($ch);
return $output;
}
$urls = array(
'http://www.wikipedia.org/',
'http://www.stackoverflow.com'
);
//or single url
//$urls = 'http://www.stackoverflow.com';
print_r ( get_data($urls) );
The problem was that I spoofed the user agent instead of using a real one, also didnt repalced " " by "+".

Resources