I am trying to get all Power BI reports while this process I sent CURL request in PHP to authenticate the user but it's throwing below error response - azure-active-directory

Please help me how to resolve this issue.
Error Response:
Array
(
[error] => invalid_grant
[error_description] => AADSTS65001: The user or administrator has not consented to use the application with ID '27ccc3c6-6560-461c-bf42-c0f3f756fa7a' named 'DrCloudEHR - East'. Send an interactive authorization request for this user and resource.
Trace ID: c137e449-e653-43d8-88f8-9abb8499b100
Correlation ID: 0b2f5c0d-ac09-49bc-81f3-b8b95a185186
Timestamp: 2020-11-20 06:10:03Z
[error_codes] => Array
(
[0] => 65001
)
[timestamp] => 2020-11-20 06:10:03Z
[trace_id] => c137e449-e653-43d8-88f8-9abb8499b100
[correlation_id] => 0b2f5c0d-ac09-49bc-81f3-b8b95a185186
[suberror] => consent_required
)
CURL REQUEST code:
$curlPostToken = curl_init();
curl_setopt_array($curlPostToken, array(
CURLOPT_URL => "https://login.windows.net/common/oauth2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
grant_type => 'password',
scope => 'openid',
prompt => 'admin_consent',
client_secret => '~-8gGXjt~Ag7_o_N0~l9.K63Iza_FA49TR',
resource => 'https://analysis.windows.net/powerbi/api',
client_id => '27ccc3c6-6560-461c-bf42-c0f3f756fa7a', // Registered App ApplicationID
username => '*********g#*******.com', // for example john.doe#yourdomain.com
password => '**********' // Azure password for above user
)
));
$tokenResponse = curl_exec($curlPostToken);
$tokenError = curl_error($curlPostToken); print_r($tokenError);
curl_close($curlPostToken);
$tokenResult = json_decode($tokenResponse, true);
print_r($tokenResult); exit;

Related

How to fix /sanctum/csrf-cookie errors

I am creating react js project with the Laravel Sanctum Axios API. When I get the sign-up page it shows the below error.
cors.php
<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie','register', 'login' ],
'allowed_methods' => [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => [
'Origin',
'Content-Type',
'Accept',
'Authorization',
'X-Requested-With',
'X-CSRF-Token',
],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
Now below error shown
Access to XMLHttpRequest at 'http://localhost:8000/sanctum/csrf-cookie' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
config/Session.php
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
];
.env file
APP_NAME="Crafty Shop"
APP_ENV=local
APP_KEY=base64:ECzTCbd8nfS6I82jRsd4sj4Bo6yJa0GRTfyTOrOoCno=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3310
DB_DATABASE=crafty
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
app.js
axios.defaults.baseURL= "http://localhost:8000/";
axios.defaults.headers.post['Content-Type'] ='application/json';
axios.defaults.headers.post['Accept'] ='application/json';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem('auth_token');
config.headers.Authorization = token ? 'Bearer ${}':'';
return config;
});
Login.js
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('api/login',data).then(res =>{
if(res.data.status === 200){
localStorage.setItem('auth_token', res.data.token);
localStorage.setItem('auth_name', res.data.username);
swal("Success", res.data.message,"success");
console.log(res.data.username);
history.push('/');
}
else if(res.data.status === 401){
swal("Warning", res.data.message,"warning");
}
else{
setLogin({...loginInput,error_list:res.data.validation_errors});
}
});
});
Sanctum.php
<?php
return [
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
'guard' => ['web'],
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'cors' => \App\Http\Middleware\CorsMiddleware::class,
],
];
You need to give access to your front localhost to send requests to the back-end API.
So I recommend you carefully follow the instructions from the laravel website:
https://laravel.com/docs/8.x/sanctum#spa-configuration
and if you would have any questions about some steps you can ask me.
But I think your problem is that your front URL cannot send requests and you have to allow it. but anyway first you have to follow the steps from the link
You MUST enable CORS on your server app.
Find out how Laravel does this.
This question may help you.
Laravel CORS

Laravel JWT return data from two tables

I am using JWT authentication via api.php
when a user login to the route
Route::post('login', 'AuthController#login');
he reached this method in auth controller
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 1000,
'user' => auth()->user()
]);
}
Here 'user' => auth()->user() is returning the data from user table,
I have another table user_Details in which all user information is saved, I want to fetch details from that table to when some one login,
Help me out please.
I have find another simple way to do that
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 1000,
'user' => auth()->user(),
'user_detail' => user_detail::where('user_id','=',auth()->user()->id)->get()
]);
}

Solr Solaruim Client->ping is failing

I am new to this stuff. I just inherited this olde system! I managed to get Solr running, and am trying to execute some old code that rebuilds the Solr data. The client ping is failing and I don't understand why.
Here is the code that is trying to initiate a re-index
// these are correct, now Solarium is falling over
// with a 404. pile of junk
print(SOLR_SERVER_HOSTNAME . "\n");
print(SOLR_SERVER_PORT . "\n");
print(SOLR_SERVER_CORE . "\n");
$options = array(
'adapteroptions' => array(
'host' => SOLR_SERVER_HOSTNAME,
'port' => SOLR_SERVER_PORT,
'core' => SOLR_SERVER_CORE,
'timeout' => 60
)
);
}
try {
// Ping the Solr server to check its availability
// create a new client. This seems to work
$this->client = new Solarium_Client($options);
if ($this->client) {
print("Solarium returned something \n");
print_r($this->client);
print("\n");
} else {
echo 'Solarium screwed the pooch';
}
// and create a ping whatever that means
// this also seems to work
$ping = $this->client->createPing();
if ($ping) {
print("ping creation worked \n");
print_r($ping);
} else {
print("ping creation failed \n");
}
// this always fails and terminate the
// program run
$this->client->ping($ping);
} catch (Solarium_Exception $e) {
print("exeption from ping request \n");
throw $e;
}
print("about to reset \n");
// Reset all filters and queries and process request params if requested
$this->reset($request);
}
The Solr admin screen is up. I have an empty collection1..
Here is the output from the trace I stuck in here
1/tmp/reindex.lock
15/01/18 17:38:54 [INFO] Index started
Index started
localhost
9999
collection1
Solarium returned something
Solarium_Client Object
(
[_options:protected] => Array
(
[adapter] => Solarium_Client_Adapter_Http
[adapteroptions] => Array
(
[host] => localhost
[port] => 9999
[core] => collection1
[path] => /solr/
[timeout] => 60
)
)
[_queryTypes:protected] => Array
(
[select] => Array
(
[query] => Solarium_Query_Select
[requestbuilder] => Solarium_Client_RequestBuilder_Select
[responseparser] => Solarium_Client_ResponseParser_Select
)
[update] => Array
(
[query] => Solarium_Query_Update
[requestbuilder] => Solarium_Client_RequestBuilder_Update
[responseparser] => Solarium_Client_ResponseParser_Update
)
[ping] => Array
(
[query] => Solarium_Query_Ping
[requestbuilder] => Solarium_Client_RequestBuilder_Ping
[responseparser] => Solarium_Client_ResponseParser_Ping
)
[mlt] => Array
(
[query] => Solarium_Query_MoreLikeThis
[requestbuilder] => Solarium_Client_RequestBuilder_MoreLikeThis
[responseparser] => Solarium_Client_ResponseParser_MoreLikeThis
)
[analysis-document] => Array
(
[query] => Solarium_Query_Analysis_Document
[requestbuilder] => Solarium_Client_RequestBuilder_Analysis_Document
[responseparser] => Solarium_Client_ResponseParser_Analysis_Document
)
[analysis-field] => Array
(
[query] => Solarium_Query_Analysis_Field
[requestbuilder] => Solarium_Client_RequestBuilder_Analysis_Field
[responseparser] => Solarium_Client_ResponseParser_Analysis_Field
)
[terms] => Array
(
[query] => Solarium_Query_Terms
[requestbuilder] => Solarium_Client_RequestBuilder_Terms
[responseparser] => Solarium_Client_ResponseParser_Terms
)
[suggester] => Array
(
[query] => Solarium_Query_Suggester
[requestbuilder] => Solarium_Client_RequestBuilder_Suggester
[responseparser] => Solarium_Client_ResponseParser_Suggester
)
)
[_pluginTypes:protected] => Array
(
[loadbalancer] => Solarium_Plugin_Loadbalancer
[postbigrequest] => Solarium_Plugin_PostBigRequest
[customizerequest] => Solarium_Plugin_CustomizeRequest
[parallelexecution] => Solarium_Plugin_ParallelExecution
[bufferedadd] => Solarium_Plugin_BufferedAdd
[prefetchiterator] => Solarium_Plugin_PrefetchIterator
)
[_pluginInstances:protected] => Array
(
)
[_adapter:protected] =>
[_requestBuilders:protected] =>
)
ping creation worked
Solarium_Query_Ping Object
(
[_options:protected] => Array
(
[resultclass] => Solarium_Result_Ping
[handler] => admin/ping
)
[_helper:protected] =>
[_params:protected] => Array
(
)
)
exeption from ping request
Failed to initialise Solr client:
Solr HTTP error: Not Found (404)
Failed to initialise Solr client: Solr HTTP error: Not Found (404)
Any hints? It's the first time I have seen this stuff.
Cheers,
Mark.
Fixed. The core name was getting flattened in another bit of code. Two constants for the same property. Two different values! – Addinall 22 secs

DB Transaction in Laravel lexical variable error

I'm currently using DB-Transaction and it throws Lexical variable error
attached here is my code:
DB::transaction(function ($request) use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}
It is working now after I remove the $request parameter in function
DB::transaction(function () use ($request) {
$salesman = new Salesman([
'operation_id' => $request->get('operation_id'),
'warehouse_id' => $request->get('warehouse_id'),
'salesman_name' => $request->get('salesman_name'),
'address' => $request->get('address'),
'contact_number' => $request->get('contact_number'),
'email_address' => $request->get('email_address'),
'area_id' => 'pending',
]);
$salesman->save();
});
return view('salesman.index');
}

Converting HttpFoundation\Response to an array

My symfony request is returning array with entity object and setstate method.
This is the dump of the array.
array (
0 =>
HealthyLiving\ApiBundle\Entity\User::__set_state(array(
'id' => 1,
'username' => 'admin',
'password' => '123',
'email' => 'batoosay#gmail.com',
'isActive' => false,
)),
)
And here is the code:
public function loginAction()
{
$restresult = $this->getDoctrine()->getRepository('ApiBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
echo '<pre>' . var_export($restresult, true) . '</pre>';die;
return new JsonResponse(
$restresult
);
}
The JsonResponse is empty because of the strange array. How do i convert this array of object to json ?
try to serialize with JMS like this:
$serializer = $this->get('jms_serializer');
return new Response(
$serializer->serialize($restresult, 'json')
);

Resources