'Laravel unexpected redirects ( 302 )

I have started a new Laravel 5.2 project, using laravel new MyApp, and added authentication via php artisan make:auth. This is intended to be a members only website, where the first user is seeded, and creates the rest (no manual user creation/password reset/etc).

These are the routes I have currently defined:

 Route::group(['middleware' => 'web'], function () {
  // Authentication Routes...
  Route::get( 'user/login',  ['as' => 'user.login',     'uses' => 'Auth\AuthController@showLoginForm']);
  Route::post('user/login',  ['as' => 'user.doLogin',   'uses' => 'Auth\AuthController@login'        ]);

  Route::group(['middleware' => 'auth'], function() {
    // Authenticated user routes
    Route::get( '/', ['as'=>'home', 'uses'=> 'HomeController@index']);
    Route::get( 'user/{uid?}', ['as' => 'user.profile',   'uses' => 'Auth\AuthController@profile' ]);
    Route::get( 'user/logout', ['as' => 'user.logout',    'uses' => 'Auth\AuthController@logout'  ]);
    Route::get( '/user/add',   ['as' => 'user.add',       'uses' => 'Auth\AuthController@showAddUser']);

    [...]
  });
});

I can login just fine, however I'm experiencing some very "funky" behavior - when I try to logout ( via the built-in logout method that was created via artisan ), the page does a 302 redirect to home, and I am still logged in.

What's more, while almost all pages (not listed here) work as expected, user.add also produces a 302 to the home page.

Do note the homepage is declared to the AuthController as $redirectTo, if that makes any difference

I found out about the redirects via the debugbar. Any idea on what to look for ?



Solution 1:[1]

I encountered an issue with 302 Redirects when posting ajax requests. The solution in this case was to remember to include the CSRF token.

See the Laravel 5.4 documents here: https://laravel.com/docs/5.4/csrf

Solution 2:[2]

I got the same issue and i solved it by adding the header with accept:'application/json'. And I think I checked the source code before which indicates that if you don't add this, it might redirect when you are using the auth middleware. But I am not sure if it is the case and I cannot recall where i found this.

Solution 3:[3]

For me it was guest middleware!

This middleware redirects user to homepage if authenticated. You don't have to use it for Api requests. So I removed it and the problem solved.

Solution 4:[4]

May be default redirect page after logout is home and seems like you do not have home in your web route. Try the below code in your AuthController.php

use AuthenticatesAndRegistersUsers, ThrottlesLogins; // after this line
$redirectAfterLogout = 'login' // add this line

This will redirect you to login page after logout. You can change it to any route if you wish. I used login as an example.

OR

You can change after logout route in \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php

public function logout()
    {
        Auth::logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : 'login');
    }

I changed the default route to login. If you don't have $redirectAfterLogout in your AuthController.php it will look here for redirect path. I don't suggest people to edit here, it's kind of hard coding.

Solution 5:[5]

I had this issue and it turned out I had a route:redirect inside my ajax controller. which doesn't make sense because obviously we have to return ajax but I was returning a route!

Solution 6:[6]

I too experienced this issue in the login page which worked fine previously. So thought have a look at the directory permissions and it resulted the following:

drwxr-xr-x  7 user user     4096 Jun 27  2019 storage

So storage directory has 755 permission which means only the owner has write access, Since that directory owned by "user" others like laravel can't write into it.

Changing the directory to 777 with this cmd resolved my issue:

sudo chmod 777 -R PROJECT_PATH/storage

The right way,

Since making that directory world-writable isn't the right way, make that directory owned by apache and set 775 to storage.. and it worked again.

sudo chown -R user:www-data PROJECT_PATH/storage
sudo chmod 775 -R PROJECT_PATH/storage

Solution 7:[7]

I use a lot ajax (get & post) and with every response I update the token with session()->regenerate() on the server, then on the client side I update every token field with js. But last week, I delete by mistake the one liner function to do that. So, suddenly the system starts to give a 302 response after the second call. It was so hard to find what was going on, because it works sometimes (firstime) and sometimes don't. After I realize it was a token mismatch, I struggle a couple of days trying to find why, because the response don't point a token mismatch, just the 302 redirect. Finally, I find the problem by dd() both tokens on the tokensMatch() function. I don't know why it won't trigger a TokenMismatch.

I hope this anecdote help you.

Solution 8:[8]

If your website doesn't use HTTPS you have to define the following attribute in your .env

SESSION_SAME_SITE=Strict

Note: this precaution applied by some browsers to prevent exploit website's users

Solution 9:[9]

For me it was this in my controller:

public function __construct()
{
   $this->middleware('admin');
}

Solution 10:[10]

For me it was config/session.php

I changed some values there for production app like path, secure, same_site

But on local due to http://localhost, Secure session was failing to create any cookies.

That's why Authenticate middleware redirecting to login page with status 302

Solution 11:[11]

I have modified my login route with adding as parameter to it and it worked for me.

Route::get('login', ['as' => 'login', 'uses' => 'loginController@index']);