Duplicated: Laravel using web authentication in all api routes redirect to home
I don't know the keyword to search it on google so sorry about something stupid. I use web route to load view and api route to load json data like this:
/shop/categories
/api/shop/categories
I logged in with web route and auth middleware check is okay, I can get user name by auth()->user()->name. But when I call jquery ajax with /api/shop/categories I get an error "Authenticated.", I try to add middleware auth:api but nothing change. I read document and I see I must include api_token url.
How do I use the api when logged in with web route, middleware check?
Here is my some code:
//web route
Route::group(['prefix' => $prefix, 'middleware' => ['auth']], function() {
Route::get('categories', 'CategoryController#getView')->name('category_get_view');
});
// api route
Route::group(['prefix' => $prefix, 'middleware' => ['auth:api']], function() {
Route::get('categories', 'CategoryController#getJson');
Route::get('categories/{category}', 'CategoryController#getDetail');
Route::put('categories/{category}', 'CategoryController#putSave');
Route::post('categories', 'CategoryController#postSave');
Route::delete('categories/{category}', 'CategoryController#deleteSave');
});
// dd($request)
Request {#42
#json: null
#convertedFiles: null
#userResolver: Closure {#399
class: "Illuminate\Auth\AuthServiceProvider"
this: AuthServiceProvider {#32 …}
parameters: {
$guard: {
default: null
}
}
use: {
$app: Application {#2 …}
}
file: "\vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php"
line: "85 to 87"
}
#routeResolver: Closure {#412
class: "Illuminate\Routing\Router"
this: Router {#25 …}
use: {
$route: Route {#181 …}
}
file: "\vendor\laravel\framework\src\Illuminate\Routing\Router.php"
line: "649 to 651"
}
+attributes: ParameterBag {#44
#parameters: []
}
+request: ParameterBag {#50
#parameters: array:2 [
"key" => null
"page" => "1"
]
}
+query: ParameterBag {#50}
+server: ServerBag {#46
#parameters: array:40 [
"REDIRECT_STATUS" => "200"
"HTTP_HOST" => "backend.local"
"HTTP_CONNECTION" => "keep-alive"
"HTTP_ACCEPT" => "*/*"
"HTTP_X_CSRF_TOKEN" => "BNlGYoppmtl7fljKeQ4TGdNmbGoiuKWTeoLDbKln"
"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
"HTTP_USER_AGENT" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
"HTTP_REFERER" => "http://backend.local/shop/categories"
"HTTP_ACCEPT_ENCODING" => "gzip, deflate"
"HTTP_ACCEPT_LANGUAGE" => "en-US,en;q=0.9,ja;q=0.8"
"HTTP_COOKIE" => "XSRF-TOKEN=eyJpdiI6IjNcL0t5aEMxZHNBM2wrNkRvc0RCUUlBPT0iLCJ2YWx1ZSI6InlaTUlLdSt4UXVmdktNZk81ZzNpMWFNQUVqalZZTmNsRmpcLzZiQkkrdTRZZEphODVPYU5qYXdiSkRVMUUra0hJIiwibWFjIjoiMTdlNjUzYmVkYWRiM2JiNDNlMWYzMjQ1MmM0ZmIxMjQ0YzczOWE4NjQ2N2UzNzZmOTkxOGYxYTJjOTE5MmU0NiJ9; laravel_session=eyJpdiI6InpLOUw5SHR6S0RWU21lSEhZMWVEZHc9PSIsInZhbHVlIjoiN1hNZUlNWUJacm83bEdFd3pCR0R1R1d1UVZZdmRcL3g3aXQ3QlhQOHNZZXFJUGVqOFBXS2dKZVFvYjl3NGZoRUsiLCJtYWMiOiI1ZjNhZmFjM2Q1ZjlmYzUwZmQ3ODA0MTJkZGNiMzdlZDhjYTljODViMTY0MTE5ZDA0YTg0ZTJkY2EwYjJmOWJmIn0%3D"
"PATH" => ""
"SystemRoot" => "C:\WINDOWS"
"COMSPEC" => "C:\WINDOWS\system32\cmd.exe"
"PATHEXT" => ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC"
"WINDIR" => "C:\WINDOWS"
"SERVER_SIGNATURE" => "<address>Apache/2.4.39 (Win64) PHP/7.2.18 Server at backend.local Port 80</address>\n"
"SERVER_SOFTWARE" => "Apache/2.4.39 (Win64) PHP/7.2.18"
"SERVER_NAME" => "backend.local"
"SERVER_ADDR" => "::1"
"SERVER_PORT" => "80"
"REMOTE_ADDR" => "::1"
"DOCUMENT_ROOT" => "/public"
"REQUEST_SCHEME" => "http"
"CONTEXT_PREFIX" => ""
"CONTEXT_DOCUMENT_ROOT" => "/public"
"SERVER_ADMIN" => "wampserver#wampserver.invalid"
"SCRIPT_FILENAME" => "/public/index.php"
"REMOTE_PORT" => "64525"
"REDIRECT_URL" => "/api/shop/categories"
"REDIRECT_QUERY_STRING" => "key=&page=1"
"GATEWAY_INTERFACE" => "CGI/1.1"
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_METHOD" => "GET"
"QUERY_STRING" => "key=&page=1"
"REQUEST_URI" => "/api/shop/categories?key=&page=1"
"SCRIPT_NAME" => "/index.php"
"PHP_SELF" => "/index.php"
"REQUEST_TIME_FLOAT" => 1570505297.533
"REQUEST_TIME" => 1570505297
]
}
+files: FileBag {#47
#parameters: []
}
+cookies: ParameterBag {#45
#parameters: array:2 [
"XSRF-TOKEN" => "eyJpdiI6IjNcL0t5aEMxZHNBM2wrNkRvc0RCUUlBPT0iLCJ2YWx1ZSI6InlaTUlLdSt4UXVmdktNZk81ZzNpMWFNQUVqalZZTmNsRmpcLzZiQkkrdTRZZEphODVPYU5qYXdiSkRVMUUra0hJIiwibWFjIjoiMTdlNjUzYmVkYWRiM2JiNDNlMWYzMjQ1MmM0ZmIxMjQ0YzczOWE4NjQ2N2UzNzZmOTkxOGYxYTJjOTE5MmU0NiJ9"
"laravel_session" => "eyJpdiI6InpLOUw5SHR6S0RWU21lSEhZMWVEZHc9PSIsInZhbHVlIjoiN1hNZUlNWUJacm83bEdFd3pCR0R1R1d1UVZZdmRcL3g3aXQ3QlhQOHNZZXFJUGVqOFBXS2dKZVFvYjl3NGZoRUsiLCJtYWMiOiI1ZjNhZmFjM2Q1ZjlmYzUwZmQ3ODA0MTJkZGNiMzdlZDhjYTljODViMTY0MTE5ZDA0YTg0ZTJkY2EwYjJmOWJmIn0="
]
}
+headers: HeaderBag {#48
#headers: array:10 [
"host" => array:1 [
0 => "backend.local"
]
"connection" => array:1 [
0 => "keep-alive"
]
"accept" => array:1 [
0 => "*/*"
]
"x-csrf-token" => array:1 [
0 => "BNlGYoppmtl7fljKeQ4TGdNmbGoiuKWTeoLDbKln"
]
"x-requested-with" => array:1 [
0 => "XMLHttpRequest"
]
"user-agent" => array:1 [
0 => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
]
"referer" => array:1 [
0 => "http://backend.local/shop/categories"
]
"accept-encoding" => array:1 [
0 => "gzip, deflate"
]
"accept-language" => array:1 [
0 => "en-US,en;q=0.9,ja;q=0.8"
]
"cookie" => array:1 [
0 => "XSRF-TOKEN=eyJpdiI6IjNcL0t5aEMxZHNBM2wrNkRvc0RCUUlBPT0iLCJ2YWx1ZSI6InlaTUlLdSt4UXVmdktNZk81ZzNpMWFNQUVqalZZTmNsRmpcLzZiQkkrdTRZZEphODVPYU5qYXdiSkRVMUUra0hJIiwibWFjIjoiMTdlNjUzYmVkYWRiM2JiNDNlMWYzMjQ1MmM0ZmIxMjQ0YzczOWE4NjQ2N2UzNzZmOTkxOGYxYTJjOTE5MmU0NiJ9; laravel_session=eyJpdiI6InpLOUw5SHR6S0RWU21lSEhZMWVEZHc9PSIsInZhbHVlIjoiN1hNZUlNWUJacm83bEdFd3pCR0R1R1d1UVZZdmRcL3g3aXQ3QlhQOHNZZXFJUGVqOFBXS2dKZVFvYjl3NGZoRUsiLCJtYWMiOiI1ZjNhZmFjM2Q1ZjlmYzUwZmQ3ODA0MTJkZGNiMzdlZDhjYTljODViMTY0MTE5ZDA0YTg0ZTJkY2EwYjJmOWJmIn0%3D"
]
]
#cacheControl: []
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/api/shop/categories"
#requestUri: "/api/shop/categories?key=&page=1"
#baseUrl: ""
#basePath: null
#method: "GET"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
Maybe you are missing Authorization in your request's header..
if you want to get data from authenticated users but want it from the api authenticated. You should get it using auth('guard-name')
Related
I am sending the id of dom element as ajax data to laravel controller but Request object is empty on the controller side. I have returned the custom array to ajax to check if controller function working and it's returning the response to ajax success.
Other functions on the same controller getting the Request data from ajax but not this function. I don't get any error so it's difficult to debug the issue
My Ajax call
$(document).on('click', 'i[id^="delete"]', function () {
var alias_id = $(this).prop('id');
//console.log(alias_id);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{ route('deletealiasname') }}",
method: "post",
data: {'alias_id': alias_id},
dataType: "json",
contentType: false,
cache: false,
processData: false,
beforeSend : function()
{
console.log(alias_id);
},
success: function (response) {
console.log(response);
}
});
});
Route:
Route::post('/deletealiasname', 'API\UserProfileController#deleteAliasName')->name('deletealiasname');
Controller:
public function deleteAliasName(Request $request)
{
$var = $request->all();
return array($var);
}
Output of dd($request)
POST http://127.0.0.1:8000/api/deletealiasname
----------------------------------------------
------------ ----------------------------------------------------
date Thu, 06 Jun 2019 17:52:53 +0000
controller "UserProfileController"
source UserProfileController.php on line 165
file app\Http\Controllers\API\UserProfileController.php
------------ ----------------------------------------------------
Illuminate\Http\Request {#43
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#282
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#40 …}
parameters: {
$guard: {
default: null
}
}
use: {
$app: Illuminate\Foundation\Application {#2 …}
}
file: "C:\project\newglit\myglit\vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php"
line: "83 to 85"
}
#routeResolver: Closure() {#284
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#26 …}
use: {
$route: Illuminate\Routing\Route {#221 …}
}
file: "C:\project\newglit\myglit\vendor\laravel\framework\src\Illuminate\Routing\Router.php"
line: "650 to 652"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag {#44
#parameters: []
}
+query: Symfony\Component\HttpFoundation\ParameterBag {#51
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#47
#parameters: array:29 [
"DOCUMENT_ROOT" => "C:\project\newglit\myglit\public"
"REMOTE_ADDR" => "127.0.0.1"
"REMOTE_PORT" => "56590"
"SERVER_SOFTWARE" => "PHP 7.1.29 Development Server"
"SERVER_PROTOCOL" => "HTTP/1.1"
"SERVER_NAME" => "127.0.0.1"
"SERVER_PORT" => "8000"
"REQUEST_URI" => "/api/deletealiasname"
"REQUEST_METHOD" => "POST"
"SCRIPT_NAME" => "/index.php"
"SCRIPT_FILENAME" => "C:\project\newglit\myglit\public\index.php"
"PATH_INFO" => "/api/deletealiasname"
"PHP_SELF" => "/index.php/api/deletealiasname"
"HTTP_HOST" => "127.0.0.1:8000"
"HTTP_CONNECTION" => "keep-alive"
"CONTENT_LENGTH" => "15"
"HTTP_CONTENT_LENGTH" => "15"
"HTTP_ACCEPT" => "application/json, text/javascript, */*; q=0.01"
"HTTP_ORIGIN" => "http://127.0.0.1:8000"
"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
"HTTP_USER_AGENT" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safar
i/537.36"
"CONTENT_TYPE" => "text/plain;charset=UTF-8"
"HTTP_CONTENT_TYPE" => "text/plain;charset=UTF-8"
"HTTP_REFERER" => "http://127.0.0.1:8000/user/profile/"
"HTTP_ACCEPT_ENCODING" => "gzip, deflate, br"
"HTTP_ACCEPT_LANGUAGE" => "en-US,en;q=0.9,nb;q=0.8"
"HTTP_COOKIE" => "XSRF-TOKEN=eyJpdiI6IkdPR0NtcGNXdEJxKzVwZERheEZSMlE9PSIsInZhbHVlIjoiXC9EbHBHSXM2U0c1TzdjUHhOT25BZ1RQeXdzd3l0WGFw
bmNhWWduakJFRU9ubVBcL3pJdzJMcTI1SCtqQnR4Sk05IiwibWFjIjoiYjk4Mzk3M2ZiOGJlOGZkOGNmYjk1NjBjZGQzNTY3YzIzOWUwNzliNDdjNjNhMzRhODZkOThmZGI2NzU
3MDc2OCJ9; laravel_session=eyJpdiI6IktNaHlnY29BZnI3VUlEcHpnUU1vU2c9PSIsInZhbHVlIjoiUkxWTkVWdHlLcEZGY0FDOXAxMWdaNHROa2szSUY3ZlhWRm94V2ox
ZWZSYlc4SDdcL3FSdUlVNGZ0YkFreHl4VHQiLCJtYWMiOiJlOGQ0MjYwZTRiN2ZkOTQwYWRmNTcxNjYyNTY0YmYyZjY5MjBkN2E3ZWMxZGM3YWViYzQ4ODcxYzUyZTg0MTE3In0
%3D"
"REQUEST_TIME_FLOAT" => 1559843573.3443
"REQUEST_TIME" => 1559843573
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#48
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\ParameterBag {#46
#parameters: array:2 [
"XSRF-TOKEN" => "eyJpdiI6IkdPR0NtcGNXdEJxKzVwZERheEZSMlE9PSIsInZhbHVlIjoiXC9EbHBHSXM2U0c1TzdjUHhOT25BZ1RQeXdzd3l0WGFwbmNhWWduakJF
RU9ubVBcL3pJdzJMcTI1SCtqQnR4Sk05IiwibWFjIjoiYjk4Mzk3M2ZiOGJlOGZkOGNmYjk1NjBjZGQzNTY3YzIzOWUwNzliNDdjNjNhMzRhODZkOThmZGI2NzU3MDc2OCJ9"
"laravel_session" => "eyJpdiI6IktNaHlnY29BZnI3VUlEcHpnUU1vU2c9PSIsInZhbHVlIjoiUkxWTkVWdHlLcEZGY0FDOXAxMWdaNHROa2szSUY3ZlhWRm94V2o
xZWZSYlc4SDdcL3FSdUlVNGZ0YkFreHl4VHQiLCJtYWMiOiJlOGQ0MjYwZTRiN2ZkOTQwYWRmNTcxNjYyNTY0YmYyZjY5MjBkN2E3ZWMxZGM3YWViYzQ4ODcxYzUyZTg0MTE3In
0="
]
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49
#headers: array:12 [
"host" => array:1 [
0 => "127.0.0.1:8000"
]
"connection" => array:1 [
0 => "keep-alive"
]
"content-length" => array:1 [
0 => "15"
]
"accept" => array:1 [
0 => "application/json, text/javascript, */*; q=0.01"
]
"origin" => array:1 [
0 => "http://127.0.0.1:8000"
]
"x-requested-with" => array:1 [
0 => "XMLHttpRequest"
]
"user-agent" => array:1 [
0 => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
]
"content-type" => array:1 [
0 => "text/plain;charset=UTF-8"
]
"referer" => array:1 [
0 => "http://127.0.0.1:8000/user/profile/"
]
"accept-encoding" => array:1 [
0 => "gzip, deflate, br"
]
"accept-language" => array:1 [
0 => "en-US,en;q=0.9,nb;q=0.8"
]
"cookie" => array:1 [
0 => "XSRF-TOKEN=eyJpdiI6IkdPR0NtcGNXdEJxKzVwZERheEZSMlE9PSIsInZhbHVlIjoiXC9EbHBHSXM2U0c1TzdjUHhOT25BZ1RQeXdzd3l0WGFwbmNhWWduak
JFRU9ubVBcL3pJdzJMcTI1SCtqQnR4Sk05IiwibWFjIjoiYjk4Mzk3M2ZiOGJlOGZkOGNmYjk1NjBjZGQzNTY3YzIzOWUwNzliNDdjNjNhMzRhODZkOThmZGI2NzU3MDc2OCJ9;
laravel_session=eyJpdiI6IktNaHlnY29BZnI3VUlEcHpnUU1vU2c9PSIsInZhbHVlIjoiUkxWTkVWdHlLcEZGY0FDOXAxMWdaNHROa2szSUY3ZlhWRm94V2oxZWZSYlc4SD
dcL3FSdUlVNGZ0YkFreHl4VHQiLCJtYWMiOiJlOGQ0MjYwZTRiN2ZkOTQwYWRmNTcxNjYyNTY0YmYyZjY5MjBkN2E3ZWMxZGM3YWViYzQ4ODcxYzUyZTg0MTE3In0%3D"
]
]
#cacheControl: []
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/api/deletealiasname"
#requestUri: "/api/deletealiasname"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
i guess the issue is with method:"post"
because it's not method object, It's actually a type.
type:"post"
Try this one
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{ route('deletealiasname') }}",
type: "post",
data: {'alias_id': alias_id},
dataType: "json",
contentType: false,
cache: false,
processData: false,
beforeSend : function()
{
console.log(alias_id);
},
success: function (response) {
console.log(response);
}
});
ANd as you said you are using laravel 5.8. so you can start your dump server in terminal for debug. jsut hit command in terminal php artisan dump-server and dd(#request)
and see data is coming or not.
am sure its issue is with method:"post" just change it with type:"post"
I haven't understood why it's happening but found a way to send data through ajax. I simply added a form element and appended my data to FormData and sent it as ajax data.
Form element
<form id="deleteAliasName" class="ui form" action="{{ route('deletealiasname') }}" method="post">
</form>
Ajax
var alias_id = $(this).attr('data-id');
formData = new FormData($('#deleteAliasName')[0]);
formData.append('alias_id', alias_id);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{ route('deletealiasname') }}",
type: "post",
data: formData,
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function (response) {
console.log(response);
}
});
Now I receiving the data in controller request
I won't mark it as accepted answer because I think it's a workaround.
i have a little problem with my json response.
I dumped it in my php code, and the result is what i attached here
How can I dump the statusText ?
I've already tried to decode it, and i've tried this too:
dump($myVar['statusText']);
or something like that
(to obtain the dump of my json i've posted, i've just did
dump($myVar); )
JsonResponse {#325
#data: "{"code":"OK","status":"ok","data":{"UUID":"f239ae18-98af-4224-8b4f-7713c71a5576","order":{something here },"orderRows":[something else here}}"
#callback: null
#encodingOptions: 271
+headers: ResponseHeaderBag {#326
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:4 [
"content-type" => "Content-Type"
"access-control-allow-origin" => "Access-Control-Allow-Origin"
"cache-control" => "Cache-Control"
"date" => "Date"
]
#headers: array:4 [
"content-type" => array:1 [
0 => "application/json; charset=utf-8"
]
"access-control-allow-origin" => array:1 [
0 => "*"
]
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Mon, 06 May 2019 08:15:28 GMT"
]
]
#cacheControl: []
}
#content: "{"code":"OK","status":"ok","data":{"UUID":"f239ae18-98af-4224-8b4f-7713c71a5576","order":{something},"orderRows":[something else}}"
#version: "1.0"
#statusCode: 200
#statusText: "OK"
#charset: null
}
Just wanna see
"status" => 'ok' and my life would be perfect :D
Looking at this output, it looks like the code is stored in the content also.
"status":"ok"
For this reason, following this documentation on the getData() method, you should be able to retrieve the status:
$data = $myVar->getData();
var_dump($data->status);
It is expected that this would return a string of "ok".
why laravel doesn't accept vars with underscore from request header?
I made a simple request example with a variable: "token_auth" with value 123 , but inside in my route doesn't get this value.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Test extends Controller
{
public function teste(Request $request){
dd($request->header());
}
}
only prints header with no underscore:
array:9 [
"thisheadernounderline" => array:1 [
0 => "312321"
]
"cache-control" => array:1 [
0 => "no-cache"
]
"postman-token" => array:1 [
0 => "3c461fd1-5bea-4100-9926-81c14cb5810c"
]
"user-agent" => array:1 [
0 => "PostmanRuntime/7.1.1"
]
"accept" => array:1 [
0 => "*/*"
]
"host" => array:1 [
0 => "localhost"
]
"cookie" => array:1 [
0 => "XSRF-TOKEN=eyJpdiI6IkJwM3pjVkFBb2hxS2d4MDFcL2srM0h3PT0iLCJ2YWx1ZSI6IiszRzhoTzV0VzN5YUkydUNUTGR5aENVd291ZW01SkZ4V2ZxQkNDTGJwbDlyMFFJZGxzNnorMkF0VUNTbHpoRndLV3FmbndJWFhkXC9cL3IzOGZvN25zN3c9PSIsIm1hYyI6IjQwZWQ1YmJhM2VjM2I3N2RiNWZlYjcwYjZmYzQ0NDk5YjkwZDc4YzRjNGQwZjQxNDVkOGU1NDU0MTA0OWI2YWYifQ%3D%3D; laravel_session=eyJpdiI6IitSckpmOFI1TmpuXC9SSUt2QVY3VlFRPT0iLCJ2YWx1ZSI6IlwvVk1EaDdYdDNxRTZLNytRcnZDTlNiaVlFTWVRVmNUOHlyVnFia0pDeE9HNWpNa3QrWlBsNnNoVEduVkhrMUhkYURoNDI4cW9RdXVHU0lIS0JZN2REQT09IiwibWFjIjoiNWJmYmJmNTdmMzJkZjQ1OGQ4NTM1NjhhMzQxNDk5NWUxOTA5OGVjOThkODkyNDgwZTA2NzEyYjFlZmE2YjVjOSJ9"
]
"accept-encoding" => array:1 [
0 => "gzip, deflate"
]
"connection" => array:1 [
0 => "keep-alive"
]
]
is there any workaround to solve this?
And I cant change this because this variable comes from an API (aready asked to change but they wont wanna change).
Already tried with laravel 5.4 and laravel 5.6.
ps: with simple php works fine (no laravel framework)
This worked for my scenario.
I used this workaround in Laravel to solve my problem:
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
output:
token_auth: 123
cache-control: no-cache
Postman-Token: f5bf7878-1f64-4ee8-907a-991d73ab8667
User-Agent: PostmanRuntime/7.1.1
Accept: */*
Host: localhost
cookie: XSRF-TOKEN=eyJpdiI6IkJwM3pjVkFBb2hxS2d4MDFcL2srM0h3PT0iLCJ2YWx1ZSI6IiszRzhoTzV0VzN5YUkydUNUTGR5aENVd291ZW01SkZ4V2ZxQkNDTGJwbDlyMFFJZGxzNnorMkF0VUNTbHpoRndLV3FmbndJWFhkXC9cL3IzOGZvN25zN3c9PSIsIm1hYyI6IjQwZWQ1YmJhM2VjM2I3N2RiNWZlYjcwYjZmYzQ0NDk5YjkwZDc4YzRjNGQwZjQxNDVkOGU1NDU0MTA0OWI2YWYifQ%3D%3D; laravel_session=eyJpdiI6IitSckpmOFI1TmpuXC9SSUt2QVY3VlFRPT0iLCJ2YWx1ZSI6IlwvVk1EaDdYdDNxRTZLNytRcnZDTlNiaVlFTWVRVmNUOHlyVnFia0pDeE9HNWpNa3QrWlBsNnNoVEduVkhrMUhkYURoNDI4cW9RdXVHU0lIS0JZN2REQT09IiwibWFjIjoiNWJmYmJmNTdmMzJkZjQ1OGQ4NTM1NjhhMzQxNDk5NWUxOTA5OGVjOThkODkyNDgwZTA2NzEyYjFlZmE2YjVjOSJ9
accept-encoding: gzip, deflate
Connection: keep-alive
I am trying to obtain a JSON response from an end point using Guzzle 6.2 with Laravel 5.3.
I am using the following code to make a get request:
$client = new GuzzleHttp\Client([
'base_uri' => 'https://192.xx.xxx.xx6/',
'timeout' => 2.0
]);
$response = $client->request('GET',
'/fineract-provider/api/v1/clients/388?tenantIdentifier=default&pretty=true', [
'verify' => false,
'auth' => ['<username>', '<password>']
]
);
var_dump($response);
Which outputs the following response:
Response {#282
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:7 [
"Server" => array:1 [
0 => "Apache-Coyote/1.1"
]
"Access-Control-Allow-Origin" => array:1 [
0 => "*"
]
"Access-Control-Allow-Methods" => array:1 [
0 => "GET, POST, PUT, DELETE, OPTIONS"
]
"Content-Type" => array:1 [
0 => "application/json"
]
"Transfer-Encoding" => array:1 [
0 => "chunked"
]
"Vary" => array:1 [
0 => "Accept-Encoding"
]
"Date" => array:1 [
0 => "Sat, 04 Feb 2017 15:51:10 GMT"
]
]
-headerNames: array:7 [
"server" => "Server"
"access-control-allow-origin" => "Access-Control-Allow-Origin"
"access-control-allow-methods" => "Access-Control-Allow-Methods"
"content-type" => "Content-Type"
"transfer-encoding" => "Transfer-Encoding"
"vary" => "Vary"
"date" => "Date"
]
-protocol: "1.1"
-stream: Stream {#280
-stream: stream resource #297
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
But this is not the response I expect. However, when I make the same request in my browser it gives the correct output as below:
What am I doing wrong here?
The Response object contains more information than just the response. You can get the actual output like this:
$output = (string)$response->getBody();
It might be necessary (in certain cases) to cast the result to a string, because the actual result is a stream.
Guzzle documentation: Responses
I am using Laravel Passport Authentication in my project. I want to use passport authentication only in API so I am trying to generate client_id and client_secret using below code but it returns NULL
I have written this code in my routes/api.php
Route::post('/gen_client', function () {
$http = new GuzzleHttp\Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $http->post(url('/') . '/oauth/clients',
['body' => json_encode(
[
'id' => 'ovais.khan#gmail.com',
'name' => 'Ovais2',
'redirect' => url('/') . '/callback'
]
)
]
);
$response_body = json_decode((string)$response->getBody(), true);
var_dump($response_body);
});
Suppose if I have generated client_id using command line php artisan passport:client
now I want to authorized access token but it returns NULL
Route::post('callback', function (Request $request) {
$http = new GuzzleHttp\Client();
$oauth_client = DB::table('oauth_clients')->where('id', '=', 'ovais.khan#gmail.com')->first();
$response = $http->post(url('/') . '/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => $oauth_client->id,
'client_secret' => $oauth_client->secret,
'redirect_uri' => url('/') . '/callback',
'code' => $request->code,
],
]);
$response_body = json_decode((string)$response->getBody(), true);
var_dump($response_body);
$access_token = $response_body['access_token'] ;
$refresh_token = $response_body['refresh_token'];
});
dd(url('/') . '/oauth/clients'); send me the output:
http://localhost/project/public/oauth/clients
dd($response); send me the output:
Response {#224
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:7 [
"Date" => array:1 [
0 => "Sat, 29 Oct 2016 10:19:24 GMT"
]
"Server" => array:1 [
0 => "Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/7.0.9"
]
"X-Powered-By" => array:1 [
0 => "PHP/7.0.9"
]
"Cache-Control" => array:1 [
0 => "no-cache"
]
"Set-Cookie" => array:1 [
0 => "laravel_session=eyJpdiI6Ikx5WXJpTEFvZ0ZiNFwvbFwvYWZRQWxEZz09IiwidmFsdWUiOiJVM29lbTNYSnZwdld5ZHdVRk1IK1hJbG9RenNQa1owS1lRMEFYQ3lVamluV3JcL2RwaVQyRkpsZzkwQ082OU94QkJiSUpGQTZpeTMxWjdpMEtCZ1Byc3c9PSIsIm1hYyI6IjQwNTcwZTQ4YzQ2OGIwODQ5Y2NjMzBiMmIyNmI5MTVkNTY0ZjI0OGQ1Y2M1NTVjYTljNmU4Mjk2Nzg0Yjk2MmMifQ%3D%3D; expires=Sat, 29-Oct-2016 12:19:24 GMT; Max-Age=7200; path=/; HttpOnly"
]
"Content-Length" => array:1 [
0 => "4709"
]
"Content-Type" => array:1 [
0 => "text/html; charset=UTF-8"
]
]
-headerNames: array:7 [
"date" => "Date"
"server" => "Server"
"x-powered-by" => "X-Powered-By"
"cache-control" => "Cache-Control"
"set-cookie" => "Set-Cookie"
"content-length" => "Content-Length"
"content-type" => "Content-Type"
]
-protocol: "1.1"
-stream: Stream {#222
-stream: stream resource #234
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
Can anyone help me out?
Waiting for positive response.
My teamlead has been resolved this problem. Please check the below link:
Laravel's 5.3 passport and api routes
The reason you are getting NULL for $response_body is when you are setting the variable you are type hinting $response->getBody() as a string, what you are actually getting is an instance of Stream. Also you're trying to json_decode a class, not a json string. $response_body = json_decode((string)$response->getBody(), true); If you would like a JSON response you can do $response_body = $response->json();
For more information these sections of the GuzzleHttp docs will be really useful:
http://guzzle3.readthedocs.io/http-client/response.html#response-body and http://guzzle3.readthedocs.io/http-client/entity-bodies.html