我正在尝试使用 tymondesigns/jwt-auth (JSON Web Token) 在 Laravel 中实现身份验证。
这是我的 auth.php 配置文件中的一些代码:
...
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
...
这是我的登录路由/api.php 文件中的一条路由:
Route::post('/login', 'AuthController@login');
这是我的 AuthController.php 文件:
class AuthController extends Controller
{
public function login() {
// $credentials = request(['email', 'password']);
$credentials = ["email" => "test@test.te", "password" => "test123"];
if (! ($token = auth()->attempt($credentials))) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
...
}
这是我的模型类 User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = 'user';
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
protected $hidden = [
'password', 'remember_token',
];
...
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public function setPasswordAttribute($password)
{
if ( !empty($password) ) {
$this->attributes['password'] = bcrypt($password);
}
}
}
auth()->attempt($credentials)
在 AuthController@login 方法中返回 false 但我确定凭据在数据库中正确。我试图清除缓存但仍然没有运气,我无法让身份验证工作。为什么这不起作用?