How to switch authentication from one user to another using Laravel

First, I log in as user X, and I have a function like:

public function loginAs($userId) { Auth::loginUsingId($userId); // now use Y user return response()->json(['logged' => Auth::check(), 'user' => Auth::user()]); } 

and when I try to print Auth::check() , it returns TRUE , which so far I have registered as user Y, the fact is that I first log in as user X and then switch to another user Y, but when I I call some other functions, it seems that the current user is still registered X, and I want to be Y of the current user registered ... This may have to do something with the session or I don’t know exactly how to do it, it would be grateful if someone had a sample or you have an idea how achieve such things in Laravel 5.

+6
source share
2 answers

Can you clarify? I was able to switch users using the following:

 use Auth; class TempController extends Controller { public function index() { $user = User::find(1); Auth::login($user); var_dump(Auth::user()->id); // returns 1 Auth::logout(); var_dump(Auth::user()); // returns null $user = User::find(2); Auth::login($user); var_dump(Auth::user()->id); // returns 2 Auth::logout(); } } 

routes.php

 Route::get('/temp', ' TempController@index '); 

If you run this, you will see that the logged in user ID has changed.

+4
source

You must use impersonation There is a blog post about this http://blog.mauriziobonani.com/easily-impersonate-any-user-in-a-laravel-application/

+1
source

All Articles