Search code examples
phplaravelapiaccess-tokenlaravel-passport

Laravel Passport between two Laravel projects


I Have one big struggle.

I'm trying to create two Laravel websites. One for frontend, and one for backend. The backend will provide API generated information to the frontend. The only one thing that is hard for me is to create the Auth and the Guard for the frontend. There are a lot of tutorials in the web for how to make the system on one Laravel project, but not in two, and on different hostings.

I set the backend by this documentation: https://laravel.com/docs/5.5/passport I test it out and everything looks fine.

The problem is comping with the frontend. I want to get rid of the database authentication and use the passport's tokens :/

Does anyone have some projects or tutorials, that i can look at? Thanks!


Solution

  • Create a users(id, created_at, updated_at) table and a User model in frontend

    use Illuminate\Foundation\Auth\User as Authenticatable;
    use App\Models\Helpers\ModelHelper;
    use Auth;
    
    class User extends Authenticatable
    {        
        //here $userData we will get from backend server
    
        public static function createAuth($userData){
            $user = new User();
            $user->name = $userData['name'];
            //all other fields
    
            Auth::login($user);
    
            return $user;
        }
    }
    

    After this create a login action in frontend and also create a login at backend server and then create personal access token at backend server and return it as json response

    Login action at Backend

    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
    
        if(Auth::attempt($credentials)){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            $success['user'] = $user;
            return response()->json(['success' => $success], $this-> successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }
    

    Frontend Login action

    public function login(Request $request)
    {
          $http = new GuzzleHttp\Client; 
    
          $response = $http->post('http://backend.local/api/login', [
                'headers' => [
                    'Accept' => 'application/json',
                ],
                'form_params' => [
                    'email' => 'username@example.vom', 
                    'password' => '123', 
                ]
            ]);
    
            $info = json_decode((string) $response->getBody(), true);
    
            $request->session()->put('authUser', $info['success']['user']); 
    
            \App\User::createAuth($info['success']['user']);
    
            return redirect('/');
    }
    

    Create a custom middleware RemoteAuth

    namespace App\Http\Middleware;
    
    use Illuminate\Auth\AuthenticationException;
    use Closure;
    use Auth;
    use App\User;
    
    class RemoteAuth
    {
        public function handle($request, Closure $next)
        {
            if (!empty(session('authUser'))) {
                $user = $request->session()->get('authUser');
    
                User::createAuth($user);
    
                return $next($request);
            }
    
            return redirect('/login');
        }
    }
    

    Register this middleware in Kernel.php in protected $routeMiddleware section.

    'remoteAuth' => \App\Http\Middleware\RemoteAuth::class
    

    Now use this remoteAuth middleware in Route

    Route::middleware('remoteAuth')->get('/test', function (Request $request) { 
        return 'Protected page'; 
    });
    

    Hope it will give you some idea.