在Laravel(PHP)中使用JWT(JSON网络令牌)进行身份验证

时间:2019-05-08 14:05:30

标签: php laravel jwt jwt-auth

我正在尝试使用tymondesigns / jwt-auth在Laravel中实现身份验证 (JSON Web令牌)。

这是我的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);
        }
    }

}
AuthController @ login方法中的

auth()->attempt($credentials)返回false,但我确定数据库中的凭据正确无误。我试图清除缓存,但仍然没有运气,我无法通过身份验证。有什么原因不起作用?

0 个答案:

没有答案