4
votes

I am using laravel 5.4 as backend for my application and for front-end I am using angular. I am using laravel auth for authentication.

Issue is Auth::attempt() is working fine and if immediately I print the Auth::user() then it prints the data but it returns false if I try to fetch it in next method. But this functionality is working fine in hosted server.

Tested,

  1. Changing session from file to database.
  2. Changes in kernel.php (Content of $middleware).
  3. Did php artisan make:auth one more time.
  4. Did changes in user table column.
  5. Adding private $primarykey = 'id' to model.
  6. Adding 'web' middleware to all routes.

This is my Controller

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;

public function login()
{
 if (Auth::attempt(['email' => $email, 'password' => $password ])) 
        {
            $response = array('response' =>'Succssfully Login!' , 'success' => true);

            return $response;
        }
 }

This is where i am using Auth::check() in the same controller

public function check() 
{
    if(Auth::check())
        $response = array('response' =>'Authenticated' , 'success'=>true);
    else
        $response = array('response' =>'UnAuthenticated' , 'success'=>false);

    return $response;    
}

I am confused because same code is working fine in hosted server but not working on localhost. Do I need to do any http related changes in laravel for this?

1
are you loading your angular index.html using blade template or its on a completely different server / p.s. is the angular app not loading from laravelAnand Siddharth

1 Answers

0
votes

In case your Angular application is outside laravel, and loading without using blade template to load your Angular app's entry point i.e. Angular's index.html then what happens is Laravel is not able to set session for the app, hence when you request for the next time your laravel is not able to recognise the session so it gives false when you call Auth::check().

To achieve authentication on external (i.e Angular app on your case) you should use either Laravel Passport's password client or JWT based authentication using https://github.com/tymondesigns/jwt-auth <- this package. (Instructions on the package's readme file)

For angular and web based app I would prefer to go with JWT.