0
votes

I am working with Laravel own authentication with CSRF tokens...

in my controller

public function __construct()
{
    $this->middleware('auth')->except('login');
}

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');
    if ($token = Auth::attempt($credentials))
    {
        // $request->session()->regenerate();
        // return response()->json(compact('token'));

        return redirect()->intended('/home');
    }

and route
Route::post('/authenticate', 'AuthController@authenticate');

It is logging me successfully and sending to home page with csrf token

but I can't get the token in authenticate method. I want to use it to authenticate REST APIs... I don't want to use JWT or other Auth methods as I want REST APIs and other UI pages (blade) in same project...

2

2 Answers

0
votes

You can use Passport in laravel to handle authentication for Rest APIs.

0
votes

You can get the passed token from the $request object.

$passedToken = $request->input('_token');

But there is no guarantee that this token is authentic. You will have to confirm it's authenticity by comparing it with your current session's token.

$sessionToken = $request->session()->token();

if (! is_string($sessionToken) || ! is_string($passedToken) || !hash_equals($sessionToken, $passedToken) ) {
    throw new \Exception('CSRF token mismatch exception');
}

return $next($request);