I using Sentinel package, Everything is fine, But when I want call Sentinel::check() and Sentinel::getUser() using ajax, it return null.
help me please :(
$currentUser = Sentinel::getUser();
$my_id = $currentUser->id;
return $my_id;
I used another way.
First add user's info into a session after logging
Session::put('city_id', $currentUser->city_id);
then goto app/Http/Kernel.php and active session on rest api routes
'api' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Session\Middleware\StartSession::class, 'throttle:60,1', 'bindings', ],
and use it in ajax call.
Related
I want to ask how can you run the auth middleware before the model binding? Currently in my 5.7 application, model binding is run before the auth. I tried creating a middlwaregroup in kernel.php as follows:
'api' => [
'throttle:10,1',
'jwt.middleware',
'bindings',
],
But still the model binding is run before the auth. Also I tried to change the order of the two middlewares in my route but nothing changed.
The answer is in:
https://laravel.com/docs/5.7/middleware#sorting-middleware
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Auth\Middleware\Authorize::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
];
IF you use explicit bindings, they may run before the auth middleware. In that case, you can use Auth::authenticate() to throw an AuthenticationException which laravel will transform into a redirect to the login page.
Route::bind('user_post', fn ($id) => Auth::authenticate()->posts()->findOrFail($id));
Route::get('posts/{user_post}', ...);
I have added into the exceptions:
protected $except = [
'pay/finish'
];
But still I am getting MethodNotAllowedException
Route is defined in web.php
Route::post('/pay/finish', ['as' => 'pay.finish', 'uses' => 'PaymentController#finish']);
The post request comes from another domain.
You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues.
However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL.
The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php
You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix.
If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request?
Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?
I have a ajax function which call a controller listed on api.php (route).
Inside this controller, I'm trying to make a user's log. So, I need to store the id user in a log table. But, when I try to access any method of Auth::user(), even being logged in, I get the exception "Unauthenticated".
I think It's a miss of sending some header information on ajax function.
Someone could help me, please?
If I am correct, api.php routes in laravel are set to uses tokens rather than the session. This means each call will require a token (specified on the user model/record) to be passed.
Using Auth::user() within web.php will work as that uses user sessions to authenticate.
You can try this one,
In your Kernel.php file add your own name like 'sessions' to the $middlewareGroups. It should contain \Illuminate\Session\Middleware\StartSession::class
Assign 'sessions' to those routes you want.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
'sessions' => [
\Illuminate\Session\Middleware\StartSession::class,
]
];
routes/api.php
Route::group(['middleware' => ['sessions']], function () {
Route::resource(...);
});
I think it must work for you
<?php echo Auth::user() ?>
or {{Auth::user()->(id)}}
I have been working with session in web controllers but never tried in api controllers.I want session works in api controllers.
here is my method in Api/TestController
public function setSession(Request $request){
// session()->put('hellos','rfer');
if(session()->has('hellos')){
return response()->json(true);
}
else{
return response()->json(false);
}
}
if I comment session->put().. The method return false.
Then I tried to register in Kernel.php like that
'api' => [
'throttle:60,1',
'bindings',
\Illuminate\Session\Middleware\StartSession::class,
],
But I still don't get what i want.
I want to set the session value from api controller for all routes of my project.
They do work. See this thread.
After updating Kernel.php with below code, delete all registered sessions from session driver (whether it's file, database, redis, etc) and browse your app again.
'api' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
....
],
I have two similiar Laravel project. This is part code of kernel.php. Both projects have same code.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
But, VerifyCsrfToken always be called although I put my route inside api middlewareGroup.
I check request header in Advanced REST Client. I found this.
First project result :
Second project result :
First result has cookie attribute in request header, but second result doesn't have
You can skip csrf token check for all your api links in app/Http/Middleware/VerifyCsrfToken.php by adding the URIs to the $except property. Example:
protected $except = [
'/api/*'
];
All the routes in routes.php are included in a route group which has the 'web' middleware applied. You should probably create another routes file and have the RouteServiceProvider load those in a group with 'api' and without the 'web' middleware applied.
If you open up your RouteServiceProvider you will see where this is happening. Check the map method to see it calling mapWebRoutes.
Use routes without any middleware and it will not require csrf token anymore.