I'm trying to implement token authentication for a Laravel project. I have the registration, logout, and middleware working, but I'm unable to validate user credentials to login. I've confirmed the user exists in the database, but Auth::guard('api')->validate($credentials)
never succeeds.
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'appUsers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'appUsers' => [
'driver' => 'eloquent',
'model' => App\Models\AppUser::class
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
app/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Models\AppUser;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
use Illuminate\Http\Request;
use Log;
class LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function guard()
{
return Auth::guard('api');
}
public function getUser(Request $request)
{
return response()->json([
'success' => true,
'body' => $this->guard()->user()
]);
}
public function postLogout()
{
$user = $this->guard()->user();
if($user) {
$user->api_token = null;
$user->save();
}
return response()->json([
'success' => true
]);
}
public function postLogin(Request $request)
{
$credentials = $request->only('email', 'password');
$authenticated = $this->guard()->validate($credentials);
if(!$authenticated) {
return response('Invalid credentials', 401);
}
$user = AppUser::where('email', $request->email)->first();
$user->api_token = str_random(60);
$user->save();
return response()->json([
'success' => true,
'body' => $user
]);
}
}
Routes/api.php
Route::get('appUser', 'Auth\LoginController@getUser');
Route::post('login', 'Auth\LoginController@postLogin');
Route::post('logout', 'Auth\LoginController@postLogout')->middleware('userAuth');
Route::post('register', 'Auth\RegisterController@postRegister');
via SimpleJ