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,
....
],
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 am developing a Laravel application. Now, I am trying to create a middleware that is checked before any routes are registered. Logically, this is what I am trying to do. I have a list of routes saved in the database. Imaging, there is a model called Redirection for it. In the middleware, I want to check, if the requested path falls into one of the redirections in the database, I will redirect to a different path. Now, I created a middleware called RedirectMiddleware. Then I registered it in the kernel class like this,
protected $middlewareGroups = [
'web' => [
RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
The problem is that when I access the route that does not exist, it renders the 404 error page without going through the middleware first. How can I create/ register a middleware which is called before any routes are registered? Or what could be the better approach to achieve what I want to achieve instead of using middleware?
In Laravel the HTTP Kernel handles the middleware registration. But to register it you have to enter the configuration as you have. In the registration in picks up the desired configuration from the App\Http\Kernel.php. In there, we need to pay attention to our namespace. Laravel only reads what is in the App\Http namespace. When you call your middleware, you are attempting to reference it in relativity as if it is within the current namespace.
protected $middlewareGroups = [
'web' => [
RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
What you need to be doing is referencing it directly. To do this you need to escape the namespace and give the path. Like so...
protected $middlewareGroups = [
'web' => [
// Your other middlewares
\App\Http\Middleware\RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
This should solve your issue. If not, let me know and post your middleware so we can see what exactly you are doing.
-- Current Laravel Docs 07/19/2019 :: https://laravel.com/docs/5.8/middleware#registering-middleware
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 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.
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.